[Talking about the drawing structure of plotly] Dynamic visualization with plotly [python]

A story about understanding the structure of plotly

What is plotly

plotly is a package that creates dynamic graphs that can be used in JavaScript, R, and Python.

A dynamic graph is a graph that can be moved as follows.

aaa.gif

You can easily create a dynamic graph by preparing the specified arguments like other functions. Javascript "plotly.js" python is sometimes called "plotly.py" to distinguish it from other plotly

Contents and movement of plotly

plotly once transforms a data frame like pandas or an array of numpy into json format and holds it. It can be executed and saved as html by javascript

If you create the following html with a text editor, a plotly bar plot will be created.


<body>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

<div id="graph" style="width: 600px; height: 400px;"></div>

<script>
  //Write the value of X
  var x = ["giraffes","orangutans","monkeys"];
  //Write the value of Y
  var y = [20,14,23];
  var data = [{ name: 'sample', x : x, y : y, type: 'bar'}];
  var layout = { legend : { showlegend : false } };
  Plotly.newPlot("graph", data, layout);
</script>

</body>

image.png

What about python?

python==3.8 plotly==4.10.0

I'll do the same with python

import plotly.express as px
fig = px.bar(x=["giraffes","orangutans","monkeys"], 
            y=[20,14,23])
fig.show()

image.png

Data frames and matrices are easier to handle and pass more smoothly in python than in html. Above all, it is completed as a function and can be executed with as little code as possible.

I mentioned earlier that it holds internal data in json type. plotly has an offline plot function, by directly inserting json format data created with python here. You can do the same as you do with the function


data2=[dict(x=["giraffes","orangutans","monkeys"], 
            y=[20,14,23],
            type='bar'
           )]

import plotly

plotly.offline.iplot({
    "data": data2
})

data2 is

[{'x': ['giraffes', 'orangutans', 'monkeys'],
  'y': [20, 14, 23],
  'type': 'bar'}]

Is held as. It is not always necessary to create it with dict or list, There is no problem if it can be formatted into data with a similar structure.

data2=[
{
  "x": [
    "giraffes",
    "orangutans",
    "monkeys"
    ],
  "y": [
    20,
    14,
    23
    ],
  "type": "bar"
}
    ]

I'll try

import plotly

plotly.offline.iplot({
    "data": data2
})

image.png

It's done.

In this way, by giving "data" and "layout" as json, which is not mentioned above, the plot is completed.

I can plot by passing the argument explained in the bar function of the official web reference. If you remember how to pass in json type, you will be able to freely change the title etc.

(If you stick to it, the effort will explode, so watch the situation there)

The official function description may also have a similar json format description, I think it will be easier to learn if you understand such a structure.

Since it's a big deal, I also talk about layout

Use scatter_geo and try to specify layout as well

import plotly
import pandas as pd
import plotly.express as px

geo_info = pd.DataFrame()

geo_info['latitude']=[36,50]
geo_info['longitude']=[140,50]
geo_info['color']=[80,5]

fig = px.scatter_geo(geo_info,
                     lat='latitude',
                     lon='longitude',
                     color='color',
                     range_color=(0, 100),
                     title='Tokyo and Paris',
                     projection="equirectangular")
fig.show()

image.png

I was able to do a good plot very easily

Try changing the display title using layout and renaming the colorbar from data By default, the name of the color bar is a rule to give the passed column name.

data1 = [dict(type='scattergeo',
              lat=geo_info['latitude'],
              lon=geo_info['longitude'],
              
              marker = dict(#size = 9, 
                            #autocolorscale=False,
                            #colorscale = 'Viridis',
                            color = geo_info['color'], 
                            colorbar = dict(title='color bar!!!')
                           )
             )]

layout1 = dict(title='Tokyo and Paris from layout',
               geo = dict(projection = dict(type ='equirectangular'),
                          showland = True,
                          #landcolor="rgb(250,250,250)",
                          #subunitcolor = "rgb(217,217,217)",
                          #countrycolor = "rgb(217,217,217)",
                          countrywidth =0.5, 
                          subunitwidth=0.5)
              )


import plotly

plotly.offline.iplot({
    "data": data1,
    "layout": layout1
})

image.png

It's done.

You will be able to customize it freely like this If you put it in the corner of your head, it will help you to understand how to use plotly.

I want to check the json format

If you want to customize but don't know how to pass json Select the plot type you want to draw from plotly chart-studio and from viwer

image.png

Select python & R

image.png

You can see the json how you are passing the data You can draw this by passing it to the offline plot

that's all

Recommended Posts

[Talking about the drawing structure of plotly] Dynamic visualization with plotly [python]
[Various image analysis with plotly] Dynamic visualization with plotly [python, image]
[Write to map with plotly] Dynamic visualization with plotly [python]
About the ease of Python
[Time series with plotly] Dynamic visualization with plotly [python, stock price]
About the features of Python
Tank game made with python About the behavior of tanks
About the basics list of Python basics
Check the existence of the file with python
About the virtual environment of python version 3.7
Drawing with Matrix-Reinventor of Python Image Processing-
Recommendation of Altair! Data visualization with Python
[Visualization of ratio] Plotly and dynamic visualization [python, pie, sunburst, sanky, treemap, fannele,]
Prepare the execution environment of Python3 with Docker
2016 The University of Tokyo Mathematics Solved with Python
Calculate the total number of combinations with python
Check the date of the flag duty with Python
[Note] About the role of underscore "_" in Python
About the behavior of Model.get_or_create () of peewee in Python
Convert the character code of the file with Python3
About the * (asterisk) argument of python (and itertools.starmap)
[Python] Determine the type of iris with SVM
[Drawing and labeling multiple graphs] Plotly dynamic visualization [python3, make subplot, xlabel, ylabel]
Extract the table of image files with OneDrive & Python
Learn Nim with Python (from the beginning of the year).
Destroy the intermediate expression of the sweep method with Python
Visualize the range of interpolation and extrapolation with python
Calculate the regression coefficient of simple regression analysis with python
Summary of the basic flow of machine learning with Python
Drawing with Python Tinker
Get the operation status of JR West with Python
A reminder about the implementation of recommendations in Python
Extract the band information of raster data with python
Logistics visualization with Python
I thought about why Python self is necessary with the feeling of a Python interpreter
Try scraping the data of COVID-19 in Tokyo with Python
I tried "gamma correction" of the image with Python + OpenCV
The story of implementing the popular Facebook Messenger Bot with python
Unify the environment of the Python development team starting with Poetry
Visualize the results of decision trees performed with Python scikit-learn
Calculate the square root of 2 in millions of digits with python
I wrote the basic grammar of Python with Jupyter Lab
Run the intellisense of your own python library with VScode.
Introducing the potential of Plotly scatter plots with practical examples
I evaluated the strategy of stock system trading with Python.
Check the scope of local variables with the Python locals function.
Let's touch the API of Netatmo Weather Station with Python. #Python #Netatmo
Solve the spiral book (algorithm and data structure) with python!
The story of rubyist struggling with python :: Dict data with pycall
[Homology] Count the number of holes in data with Python
Try to automate the operation of network devices with Python
Rewrite the record addition node of SPSS Modeler with Python.
Estimate the attitude of AR markers with Python + OpenCV + drone
Play with the password mechanism of GitHub Webhook and Python
Get the source of the page to load infinitely with python.
[Python] What do you do with visualization of 4 or more variables?
Towards the retirement of Python2
About the Python module venv
About the enumerate function (python)
About various encodings of Python 3
About the components of Luigi