[Python] Make a graph that can be moved around with Plotly

Introduction

Describes the basic usage of Plotly, a library that can be used from Python. As you can see from the Link sample, Plotly allows you to create a huge variety of ** squiggly ** graphs. ..

In addition, Plotly has a function that allows you to edit and publish the created graph on the Web. This time we will ** run everything locally **.

Execution environment

Installation

pip install plotlyInstall plotly with.

Data capture

As an example, [Wikipedia](https://ja.wikipedia.org/wiki/%E6%97%A5%E6%9C%AC%E3%81%AE%E4%BA%BA%E5%8F%A3% Let's graph the data on the number of births and the birth rate for each year in Japan, picked up from E7% B5% B1% E8% A8% 88). Place the following data as birth.csv in the same folder as the Jupyter file.

year,births,birth rate
2000,1190547,1.36
2001,1170662,1.33
2002,1153855,1.32
2003,1123610,1.29
2004,1110721,1.29
2005,1062530,1.26
2006,1092674,1.32
2007,1089818,1.34
2008,1091156,1.37
2009,1070035,1.37
2010,1071304,1.39
2011,1050806,1.39
2012,1037101,1.41
2013,1029816,1.43
2014,1003532,1.42
2015,1005656,1.46

Pandas is useful for capturing and manipulating data. Pandas is included automatically when you install Anaconda.

import pandas as pd
raw = pd.read_csv("birth.csv")

Creating a graph

Initialization

First, execute the following code to plot inside Jupyter. Not required if you do not want to display it inside Jupyter. If you set connected to True in the argument, you will get Plotly's Javascript from the Internet.

import plotly
plotly.offline.init_notebook_mode(connected=False)

Specifying the data to plot

Then specify the data to plot. This time, the number of births is represented by a bar graph, and the birth rate is represented by a line graph. Prepare an array called data, and if it is a bar graph, plotly.graph_objs.Bar, If it is a line graph, specify the X-axis and Y-axis data and series name in plotly.graph_objs.Scatter. You can plot on the second axis by specifying yaxis =" y2 ".

data = [
    plotly.graph_objs.Bar(x=raw["year"], y=raw["births"], name="Births"),
    plotly.graph_objs.Scatter(x=raw["year"], y=raw["birth rate"], name="Birth Rate", yaxis="y2")
]

Specifying the graph layout

Next, specify the layout of the graph. Set the title of the graph, the position of the legend, and the second axis.

layout = plotly.graph_objs.Layout(
    title="Births and Birth Rate in Japan",
    legend={"x":0.8, "y":0.1},
    xaxis={"title":"Year"},
    yaxis={"title":"Births"},
    yaxis2={"title":"Birth Rate", "overlaying":"y", "side":"right"},
)

plot

If you want to display it in Jupyter, call ʻiplotto create a graph. If you want to display it outside Jupyter or create HTML, callplot. If you do not specify a file name as an option, `` temp-plot.html``` will be created in the same folder.

fig = plotly.graph_objs.Figure(data=data, layout=layout)
plotly.offline.iplot(fig)
#plotly.offline.plot(fig)

A graph like this will be created. aa.gif

Click here for easy operation

Other options

The size of the graph area

layout = plotly.graph_objs.Layout(
    width=800, height=600,
)

Maximum and minimum values of the axis

If you just want to set the maximum and minimum values, specify the range option for ʻaxis. If you want to start the scale from scratch, or if you don't want to display negative numbers, Specify " to zero "or" non-negative "for therange mode` option.

layout = plotly.graph_objs.Layout(
    xaxis={"title":"Year", "range": [2010, 2016]}, #from year 2010 to 2016
    yaxis={"title":"Births", "rangemode":"tozero"}, #starts from zero
)

font

The font-family should be the same as specified in CSS.

layout = plotly.graph_objs.Layout(
    font={"family":"Yu Gothic Bold, sans-selif", "size":20},
)

others

In addition, Plotly allows you to specify details. For these options, see the Plotly site (https://plot.ly/python/#layout-options) or google for them.

Remove unwanted buttons and "Edit in Plotly" on the toolbar

For data that you don't want to leak to the outside, it's nice to see the "Save and edit plot in cloud" and "Ploduced with Plotly" buttons and the "Export to plot.ly" link in the graph you created. It's not good. Therefore, I will not display these.

buttons.png

First, you can delete "Export to plot.ly" by specifying show_link = False when plotting.

plotly.offline.iplot(fig, show_link=False)
#plotly.offline.plot(fig, show_link=False)

On the other hand, options to hide the toolbar buttons are ~~ StackOverflow Posts and [ Seeing that the associated pull request (https://github.com/plotly/plotly.py/pull/410) isn't merged, it doesn't seem to exist. So, let's edit plotly.min.js in the Plotly folder, which is loaded by ʻinit_notebook_mode`. ~~ Before I knew it, I was able to pass it as an argument of iplot.

plotly.offline.iplot(fig, show_link=False, config={"displaylogo":False, "modeBarButtonsToRemove":["sendDataToCloud"]})

You can erase it by doing.

Pandas Dataframe plot

Using the library Cufflinks, you can draw a Plotly graph of Dataframe just by writing df.iplot (). See [Python] Plotly draw Pandas dataframes in one shot with Cufflinks.

Plotly conversion of matplotlib

You can change a graph written in matplotlib.pyplot to an interactive graph in Plotly just by typing ʻiplot_mpl (fig)`.

import matplotlib.pyplot as plt
import plotly.offline

plotly.offline.init_notebook_mode()

fig = plt.figure()
plt.plot([1,3,4,2,1,3])
plotly.offline.iplot_mpl(fig)

However, if you want to add a legend, you need to add some effort, so is it still under development?

import matplotlib.pyplot as plt
import plotly.offline
import plotly.tools

plotly.offline.init_notebook_mode()

fig = plt.figure()
plt.plot([1,3,4,2,1,3], label="legend")
plt.title("title")
# plt.legend()I don't need
plotly_fig = plotly.tools.mpl_to_plotly( fig )
plotly_fig['layout']['showlegend'] = True
plotly.offline.iplot(plotly_fig, show_link=False)

(For copying when you want to draw a line graph for the time being)

import plotly
plotly.offline.init_notebook_mode()
data = [
    plotly.graph_objs.Scatter(y=[2,3,1,2,5,2], name="legend"),
    plotly.graph_objs.Scatter(x=[1,2,3,4,5,6], y=[1,2,3,2,3,1], name="legend2"),
]
layout = plotly.graph_objs.Layout(
    title="title",
    xaxis={"title":"xlabel"},
    yaxis={"title":"ylabel"},
)
fig = plotly.graph_objs.Figure(data=data, layout=layout)
plotly.offline.iplot(fig, show_link=False)

Recommended Posts

[Python] Make a graph that can be moved around with Plotly
Make a currency chart that can be moved around with Plotly (2)
Make a currency chart that can be moved around with Plotly (1)
Draw a graph that can be moved around with HoloViews and Bokeh
Let's make a graph with python! !!
Make a nice graph with plotly
Let's make a diagram that can be clicked with IPython
Make a Spinbox that can be displayed in Binary with Tkinter
I made a shuffle that can be reset (reverted) with Python
Make a Spinbox that can be displayed in HEX with Tkinter
A memo that made a graph animated with plotly
How to make a rock-paper-scissors bot that can be easily moved (commentary)
Create a web app that can be easily visualized with Plotly Dash
[Python] Draw elevation data on a sphere with Plotly and draw a globe that can be rotated round and round
Moved Raspberry Pi remotely so that it can be LED attached with Python
Python knowledge notes that can be used with AtCoder
I made a familiar function that can be used in statistics with Python
Make a fortune with Python
Let's make a GUI with python.
Make a recommender system with python
If you know Python, you can make a web application with Django
I made a package that can compare morphological analyzers with Python
[Python] A program that creates stairs with #
Let's make a shiritori game with Python
Let's make a voice slowly with Python
Understand the probabilities and statistics that can be used for progress management with a python program
[Python] A program that finds the maximum number of toys that can be purchased with your money
A typed world that begins with Python
Let's make a web framework with Python! (1)
Make a desktop app with Python with Electron
Let's make a Twitter Bot with Python!
Let's make a web framework with Python! (2)
I created a template for a Python project that can be used universally
[Python] A program that finds a pair that can be divided by a specified value
Mathematical optimization that can be used for free work with Python + PuLP
I made a module PyNanaco that can charge nanaco credit with python
[Python] Code that can be written with brain death at the beginning when scraping as a beginner
Get a list of camera parameters that can be set with cv2.VideoCapture and make it a dictionary type
File types that can be used with Go
Make a Twitter trend bot with heroku + Python
[Python] Make a game with Pyxel-Use an editor-
[Python] Draw a directed graph with Dash Cytoscape
I want to make a game with Python
Create a page that loads infinitely with python
You can easily create a GUI with Python
Try to make a "cryptanalysis" cipher with Python
[Python] Make a simple maze game with Pyxel
List packages that can be updated with pip
Let's replace UWSC with Python (5) Let's make a Robot
Try to make a dihedral group with Python
A memo for making a figure that can be posted to a journal with matplotlib
A class for PYTHON that can be operated without being aware of LDAP
I want to create a priority queue that can be updated in Python (2.7)
I registered PyQCheck, a library that can perform QuickCheck with Python, in PyPI.
Around the authentication of PyDrive2, a package that operates Google Drive with Python
Since python is read as "Pichon", it can be executed with "Pichon" (it is a story)
Format DataFrame data with Pytorch into a form that can be trained with NN
How to install a Python library that can be used by pharmaceutical companies
Get the stock price of a Japanese company with Python and make a graph
If you want to make a Windows application (exe) that can be actually used now using only Python
Article that can be a human resource who understands and masters the mechanism of API (with Python code)