Python crawls the stock data of "Sorrow's mother does not recognize" and draws a visual graph

Preface

The text and pictures in this article are from the Internet and are for learning and communication purposes only, and do not have any commercial use. If you have any questions, please contact us for processing.

The following article comes from what you can call me Caige, the author Caige

Hello everyone, last time we tried to draw a tree-shaped heat map in excel with vba , but when I was drawing all 4000+ stocks, I waited 1 hour for the final rendering to be far from complete, so what should I do?

Finally, in the recent study of plotly , I found treemap in the advanced chart, which can meet my needs very well. The following is the final rendering, is it great!

Python crawls the stock data of "Sorrow's mother does not recognize" and draws a visual graph

 

Look at this picture, I'm going to cry again, I've gotten a lot of liquor! ! Hope to rise and rise quickly! ! !

table of Contents:

  • 1. Preparation
  • 2. Start drawing
    • 2.1. Simple example
    • 2.2. Introduction to common parameters of px.treemap
    • 2.3. color_continuous_scale parameter introduction
    • 2.4. The big A stock market tree-like heat map is coming
    • 2.5. Save plotly pictures locally

Python crawler, data analysis, website development and other case tutorial videos are free to watch online

https://space.bilibili.com/523606542 

Python learning exchange group: 1039645993

1. Preparation

I am here to demonstrate the plotly chart in jupyterlab. If only plotly is installed, the chart cannot be displayed normally (it will be blank), we need to make the following preparations (the following commands can all be operated under cmd):

# 安装plotly库及plotly-orca库
pip install plotly
pip install plotly plotly-orca

# Basic JupyterLab renderer support
jupyter labextension install jupyterlab-plotly

# OPTIONAL: Jupyter widgets extension for FigureWidget support
jupyter labextension install @jupyter-widgets/jupyterlab-manager plotlywidget

Reference:
https://github.com/plotly/plotly.py

Regarding the data used in this article, you can refer to the crawler code of "Python to crawl the latest stock data and use excel to draw a tree diagram" to crawl it yourself, or reply to the official account to get 0302!

2. Start drawing

There are two ways to draw Treemap, one is under plotly.express, the other is under go.Treemap, we use the former here. As for the difference, it is probably that the former is an advanced version, which encapsulates a lot of complex operations of the latter, and you can directly use the pandas.Dataframe type, which is now the main recommendation. You can feel more differences in the process of practice, after all, Cai Ge didn't quite understand it!

2.1. Simple example

Plotly comes with a lot of test data, we use one of them to try the simple one.

import plotly.express as px

df = px.data.tips()
df.head()

Python crawls the stock data of "Sorrow's mother does not recognize" and draws a visual graph

 

The above data is roughly the amount of money paid by people of different genders and the number of tips on what day of the week, and we use one line of code to draw a simple treemap as follows:

fig = px.treemap(df, path=['day', 'time', 'sex'], values='total_bill')
fig.show()

Python crawls the stock data of "Sorrow's mother does not recognize" and draws a visual graph

 

It can be seen that in the tree diagram, the levels are day, time, and sex in the order in the path, and the area of ​​each color block is the total_bill given by values. When you hover the mouse, more detailed information will appear. After all, plotly is interactive , so I won’t expand it here.

So, what else can px.treemap do? Let's continue reading.

2.2. Introduction to common parameters of px.treemap

Let us directly use? in jupyterlab to get the function parameters !

# px.treemap?

# Signature:
px.treemap(
    data_frame=None, # 就是你要用到的数据,
    names=None, # 暂时不用
    values=None, # 就是你色块大小
    parents=None, # 暂时也不用,和names组合出现吧
    ids=None, # 暂时不用,后续暂时不用的字段我就不写啦
    path=None, # 层级,依次排开
    color=None, # 颜色,比如根据 涨跌幅字段来设置颜色
    color_continuous_scale=None, # 自带的颜色尺卡,后面会介绍
    range_color=None, # 颜色范围区间,超过就是两端值
    color_continuous_midpoint=None, # 颜色尺卡最中间 的值,比如涨跌幅中间设置为 0 最合适
    color_discrete_sequence=None, 
    color_discrete_map=None,
    hover_name=None,
    hover_data=None, # 就是悬停时 显示字段及其格式
    custom_data=None, # 额外的想显示的数据
    labels=None,
    title=None, # 标题咯
    template=None,
    width=None, # 图高
    height=None, # 图长
    branchvalues=None,
    maxdepth=None, 
)

For more information about the parameters, you can look at it yourself. It’s pretty detailed, but I think it’s pretty tiring to combine translation software in pure English.

2.3. color_continuous_scale parameter introduction

We mentioned above that this parameter is the color card used for the color of our treemap map. What are the specific options and what are these options?

We found the direction in ?:

color_continuous_scale: list of str
    Strings should define valid CSS-colors This list is used to build a
    continuous color scale when the column denoted by `color` contains
    numeric data. Various useful color scales are available in the
    `plotly.express.colors` submodules, specifically
    `plotly.express.colors.sequential`, `plotly.express.colors.diverging`
    and `plotly.express.colors.cyclical`.

We called the methods mentioned in jupyterlab and were very happy to find them:

import plotly
# 大家不要急,一个个来,我这里预览只截取了diverging的部分
plotly.express.colors.cyclical.swatches()
plotly.express.colors.sequential.swatches()
plotly.express.colors.diverging.swatches()

Python crawls the stock data of "Sorrow's mother does not recognize" and draws a visual graph

 

Since in our country, green represents a decline, and red represents a rise. After searching for a long time, I chose Geyser. Of course, everyone can choose by themselves.

Python crawls the stock data of "Sorrow's mother does not recognize" and draws a visual graph

 

2.4. The big A stock market tree-like heat map is coming

Based on the above understanding, I found that it is almost ready to draw a picture, then come on!

import plotly.express as px

fig = px.treemap(df, 
                 path=['板块', '企业名称',],  # 指定层次结构,每一个层次都应该是category型的变量
                 values='市值(亿)', # 需要聚合的列名
                 color='涨幅', 
                 range_color = [-0.05, 0.05], # 色彩范围最大最小值
                 hover_data= {'涨幅':':.2%',
                             '市值(亿)':':.2f'}, # 鼠标悬浮显示数据的格式
                 height = 1080,
                 width = 1920,
                 color_continuous_scale='Geyser',
                 color_continuous_midpoint=0 , # 颜色变化中间值设置为增长率=0
                )
fig.update_traces(textinfo='label+value',textfont = dict(size = 24)) # 显示企业名称和市值,字体24
fig.show()

Python crawls the stock data of "Sorrow's mother does not recognize" and draws a visual graph

 

2.5. Save plotly pictures locally

This refers to pictures, not html files!

Everyone still remember that we installed orca during the preparation work. It's okay. If you don't remember, just reinstall it.

pip install plotly plotly-orca

For the plotly chart objects we have drawn, the following methods can be saved locally.

import plotly.io as pio

pio.write_image(fig, '树状云图png')

Of course, if you find it troublesome, you can actually click on the camera at the top right corner of the chart to download it!

Python crawls the stock data of "Sorrow's mother does not recognize" and draws a visual graph

Guess you like

Origin blog.csdn.net/m0_48405781/article/details/114668494