- Visualization with Plotly.Express: Comprehensive guide
- One dataset and over 70 charts. Interactivity and animation often in a single line of code
- Installing Plotly Express
- Библиотека Plotly в Python
- Библиотека графиков
- Почему стоит выбрать Plotly?
- Начало работы
- Установка
- Использование
- Тестовая установка
- Создание простого графика
- Базовые диаграммы
- Точечная диаграмма
- Линия и точечная диаграмма
- Коробчатые графики
- Контурные графики
- Финансовые графики
- График временных рядов
- График OHLC
- Заключение
- Saved searches
- Use saved searches to filter your results more quickly
- License
- plotly/plotly_express
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
Visualization with Plotly.Express: Comprehensive guide
One dataset and over 70 charts. Interactivity and animation often in a single line of code
I frequently come up with an ideal visualization and then struggle to code it. It would be to the point, expressive, and easy to interpret, but it’s impossible to create. When I found Plotly it made plotting, well, much easier.
Plotly.Express, first introduced in version 4.0.0 is a high-level abstraction to Plotly API optimized to work perfectly with data frames. It’s very good, though not flawless. I see the biggest gap in the number of examples or links to the API documentation. That’s why I have decided to use my experience with the library to write a guide.
To run the chart and exercises, please use the Plotly Express — Comprehensive Guide.ipynb notebook on Github. All the code in this article is in python.
- Installation — and dependencies
- Plotly.Express syntax — one line of code
- Data matters — should we pre-processed data into a wide or a long-form?
- Line Chart — used for a gentle introduction, understanding the input data and parameters we can pick to customize the chart
- Layout — templates and styling
- Annotation — to help you describe the data
- Chart types — scatter, bar, histogram, pie, donut, sunburst, treemap, maps with choropleth,
- Interactions — Buttons changing the chart
- Pitfalls — and other things to improve
- Summary of the documentation
Installing Plotly Express
Plotly.Express is a regular part of the Plotly python package, so the easiest is to install it all.
# pip
pip install plotly# anaconda
conda install -c anaconda plotly
Plotly Express also requires pandas to be installed, otherwise, you will get this error when you try to import it.
[In]: import plotly.express as px
[Out]: ImportError: Plotly express requires pandas to be installed.
Библиотека Plotly в Python
Plotly (в URL-адресе Plot.ly) – технологическая компания, базирующаяся в Монреале. Она известна разработкой и предоставлением инструментов онлайн-аналитики, статистики и построения графиков для частных лиц или компаний. Также разрабатывает и предоставляет библиотеки научного построения графиков для Arduino, Julia, MATLAB, Perl, Python, R и REST.
Библиотека графиков
Библиотека Plotly в Python делает интерактивные графики онлайн и позволяет нам сохранять их в автономном режиме, если это необходимо.
Почему стоит выбрать Plotly?
У Plotly есть несколько удивительных функций, которые делают его лучше, чем другие графические библиотеки:
- По умолчанию он интерактивен.
- Диаграммы не сохраняются как изображения, а сериализуются как JSON, что делает их открытыми для чтения с помощью R, MATLAB, Julia и других.
- Вектор экспорта для печати и публикации.
- Легко манипулировать и встраивать в Интернет.
Начало работы
Нам нужен PIP (установщик пакетов в python), чтобы начать работать с plotly, нам также нужно будет создать учетную запись на случай, если мы захотим использовать онлайн-возможности. В этом уроке мы будем использовать только офлайн.
Установка
Чтобы установить plotly, откройте окно терминала и выполните следующую команду:
Это может занять несколько минут, чтобы собрать зависимости и загрузить их:
Использование
Чтобы использовать plotly в любом из скриптов Python, нам нужно будет импортировать plotly как:
Еще несколько шагов, и вы готовы к работе. Для использования в сети вам необходимо настроить учетные данные. Это можно сделать так:
plotly.tools.set_credentials_file(username='YourUsernameHere', api_key='YourAPIkeyHere')
Для автономного использования нам нужно вызвать plot, как показано ниже, для автономного использования:
Тестовая установка
Прежде чем мы сможем начать использовать plotly, давайте протестируем его установку с помощью простого скрипта:
import plotly print(plotly.__version__)
Давайте посмотрим на результат этой программы:
Как и ожидалось, возвращается последняя версия plotly.
Создание простого графика
Начнем с простой программы «Hello, World» с примером фрагмента кода:
import plotly from plotly.graph_objs import Scatter, Layout plotly.offline.plot(< "data": [Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])], "layout": Layout(title="hello world") >)
Давайте посмотрим на результат этой программы:
Как ясно видно, этот график сохраняется как файл HTML в том же каталоге, что и сценарий.
Базовые диаграммы
Чтобы начать визуализацию данных, мы начнем с базовых диаграмм с использованием Plotly, а затем перейдем к более сложным примерам, которые показывают построение графиков, связанных со временем.
Точечная диаграмма
Мы создадим базовую диаграмму на основе некоторых случайных данных с помощью numpy. Если numpy не установлен на вашем компьютере, установите его с помощью этой команды:
Вот пример программы, показывающей диаграмму рассеяния:
import plotly import plotly.graph_objs as go # Create random data with numpy import numpy as np N = 1000 random_x = np.random.randn(N) random_y = np.random.randn(N) # Create a trace trace = go.Scatter( x = random_x, y = random_y, mode = 'markers' ) data = [trace] # Plot and embed in ipython notebook! plotly.offline.plot(data, filename='basic-scatter')
Давайте посмотрим на результат этой программы:
В этом сценарии мы также предоставили имя для HTML-файла.
Линия и точечная диаграмма
Мы можем создать более сложные и информативные графики, такие как график линейного разброса, аналогичным образом, как указано выше:
import plotly import plotly.graph_objs as go # Create random data with numpy import numpy as np N = 100 random_x = np.linspace(0, 1, N) random_y0 = np.random.randn(N)+5 random_y1 = np.random.randn(N) random_y2 = np.random.randn(N)-5 # Create traces trace0 = go.Scatter( x = random_x, y = random_y0, mode = 'markers', name = 'markers' ) trace1 = go.Scatter( x = random_x, y = random_y1, mode = 'lines+markers', name = 'lines+markers' ) trace2 = go.Scatter( x = random_x, y = random_y2, mode = 'lines', name = 'lines' ) data = [trace0, trace1, trace2] plotly.offline.plot(data, filename='scatter-mode')
Давайте посмотрим на результат этой программы:
Этот график намного информативнее, чем кажется сейчас. Наведите указатель мыши на любую точку на графике, и вы увидите дополнительную информацию об этой точке:
Коробчатые графики
Коробчатые диаграммы довольно информативны и полезны, особенно когда вам нужно показать слишком много из очень небольшого количества данных. Попробуем создать:
import random import plotly from numpy import * N = 30. # Number of boxes # generate an array of rainbow colors by fixing the saturation and lightness of the HSL representation of colour # and marching around the hue. c = ['hsl('+str(h)+',50%'+',50%)' for h in linspace(0, 360, N)] # Each box is represented by a dict that contains the data, the type, # and the colour. # Use list comprehension to describe N boxes, each with a different colour and # with different randomly generated data: data = [ < 'y': 3.5*sin(pi * i/N) + i/N+(1.5+0.5*cos(pi*i/N))*random.rand(10), 'type':'box', 'marker':> for i in range(int(N))] # format the layout layout = , 'yaxis': , 'paper_bgcolor': 'rgb(233,233,233)', 'plot_bgcolor': 'rgb(233,233,233)', > plotly.offline.plot(data)
Давайте посмотрим на результат этой программы:
Мы снова переместили указатель мыши на одну из точек, чтобы изучить дополнительную информацию об этой точке.
Контурные графики
Контурные графики – одни из наиболее часто используемых научных графиков:
from plotly import tools import plotly import plotly.graph_objs as go trace0 = go.Contour( z=[[2, 4, 7, 12, 13, 14, 15, 16], [3, 1, 6, 11, 12, 13, 16, 17], [4, 2, 7, 7, 11, 14, 17, 18], [5, 3, 8, 8, 13, 15, 18, 19], [7, 4, 10, 9, 16, 18, 20, 19], [9, 10, 5, 27, 23, 21, 21, 21], [11, 14, 17, 26, 25, 24, 23, 22]], line=dict(smoothing=0), ) trace1 = go.Contour( z=[[2, 4, 7, 12, 13, 14, 15, 16], [3, 1, 6, 11, 12, 13, 16, 17], [4, 2, 7, 7, 11, 14, 17, 18], [5, 3, 8, 8, 13, 15, 18, 19], [7, 4, 10, 9, 16, 18, 20, 19], [9, 10, 5, 27, 23, 21, 21, 21], [11, 14, 17, 26, 25, 24, 23, 22]], line=dict(smoothing=0.85), ) data = tools.make_subplots(rows=1, cols=2, subplot_titles=('Without Smoothing', 'With Smoothing')) data.append_trace(trace0, 1, 1) data.append_trace(trace1, 1, 2) plotly.offline.plot(data)
Давайте посмотрим на результат этой программы:
Такие графики часто используются при отображении данных тепловой карты.
Финансовые графики
Финансовые графики намного сложнее читать, но их легко создавать с помощью Plotly. Давайте посмотрим, какие типы диаграмм можно создать с помощью Plotly.
График временных рядов
Начнем с графика временных рядов. Мы будем использовать образцы данных самого Plotly, которые обслуживаются репозиторием Github. Вот пример программы:
import plotly import plotly.graph_objs as go import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv") data = [go.Scatter( x=df.Date, y=df['AAPL.Close'])] plotly.offline.plot(data)
Давайте посмотрим на результат этой программы:
Если pandas не установлен на вашем компьютере, установите его с помощью этой команды:
График OHLC
Диаграммы OHLC также являются отличным способом объяснить данные, относящиеся к временным рядам, для неравномерного распределения. Посмотрим на фрагмент кода:
import plotly import plotly.graph_objs as go from datetime import datetime open_data = [33.0, 33.3, 33.5, 33.0, 34.1] high_data = [33.1, 33.3, 33.6, 33.2, 34.8] low_data = [32.7, 32.7, 32.8, 32.6, 32.8] close_data = [33.0, 32.9, 33.3, 33.1, 33.1] dates = [datetime(year=2013, month=10, day=10), datetime(year=2013, month=11, day=10), datetime(year=2013, month=12, day=10), datetime(year=2014, month=1, day=10), datetime(year=2014, month=2, day=10)] trace = go.Ohlc(x=dates, open=open_data, high=high_data, low=low_data, close=close_data) data = [trace] plotly.offline.plot(data, filename='ohlc_datetime')
Посмотрим на результат этой программы:
Заключение
В этом уроке мы изучили еще одну отличную библиотеку Plotly в Python, которая используется для визуализации и автономного использования.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Plotly Express — Simple syntax for complex charts. Now integrated into plotly.py!
License
plotly/plotly_express
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Plotly Express is now part of Plotly.py version 4 and so the plotly_express module now just re-exports the contents of plotly.express
If you follow the plotly Getting Started instructions for installation, you will get access to plotly.express .
However, if you have existing code that imports from plotly_express explicitly and you don’t wish to change it, you can still install the latest version, which just exposes plotly.express under the plotly_express namespace.
Just running pip install plotly_express==0.4.1 in your terminal should do it!
You’ll have to install from the plotly channel with conda install -c plotly plotly_express==0.4.1
Please join our Community Forum or file a Github Issue if you’ve found a bug.
About
Plotly Express — Simple syntax for complex charts. Now integrated into plotly.py!