24 Pandas怎样结合Pyecharts绘制交互性折线图?
背景:
- Pandas是Python用于数据分析领域的超级牛的库
- Echarts是百度开源的非常好用强大的可视化图表库,Pyecharts是它的Python库版本
1、读取数据
import pandas as pd
xlsx_path = "./datas/stocks/baidu_stocks.xlsx"
df = pd.read_excel(xlsx_path, index_col="datetime", parse_dates=True)
df.head()
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
<pre><code>.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</code></pre>
code | open | close | high | low | vol | p_change | |
---|---|---|---|---|---|---|---|
datetime | |||||||
2019-12-03 | BIDU | 115.199997 | 114.800003 | 116.019997 | 113.300003 | 3493249 | -2.25 |
2019-12-02 | BIDU | 118.389999 | 117.440002 | 119.764999 | 116.400002 | 2203313 | -0.92 |
2019-11-29 | BIDU | 118.300003 | 118.529999 | 118.690002 | 117.599998 | 1917004 | -0.82 |
2019-11-27 | BIDU | 119.180000 | 119.510002 | 119.839996 | 118.440002 | 2341070 | 0.77 |
2019-11-26 | BIDU | 120.010002 | 118.599998 | 120.440002 | 118.099998 | 3813176 | -1.43 |
df.index
DatetimeIndex(['2019-12-03', '2019-12-02', '2019-11-29', '2019-11-27',
'2019-11-26', '2019-11-25', '2019-11-22', '2019-11-21',
'2019-11-20', '2019-11-19',
...
'2019-01-15', '2019-01-14', '2019-01-11', '2019-01-10',
'2019-01-09', '2019-01-08', '2019-01-07', '2019-01-04',
'2019-01-03', '2019-01-02'],
dtype='datetime64[ns]', name='datetime', length=227, freq=None)
df.sort_index(inplace=True)
df.head()
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
<pre><code>.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</code></pre>
code | open | close | high | low | vol | p_change | |
---|---|---|---|---|---|---|---|
datetime | |||||||
2019-01-02 | BIDU | 156.179993 | 162.250000 | 164.330002 | 155.490005 | 2996952 | NaN |
2019-01-03 | BIDU | 158.750000 | 154.710007 | 159.880005 | 153.779999 | 3879180 | -4.65 |
2019-01-04 | BIDU | 157.600006 | 160.949997 | 162.429993 | 157.250000 | 3847497 | 4.03 |
2019-01-07 | BIDU | 162.600006 | 162.600006 | 164.490005 | 158.509995 | 3266091 | 1.03 |
2019-01-08 | BIDU | 162.190002 | 163.399994 | 163.889999 | 158.160004 | 3253361 | 0.49 |
2、使用Pyecharts绘制折线图
# 如果没有安装,使用pip install pyecharts安装
from pyecharts.charts import Line
from pyecharts import options as opts
# 折线图
line = Line()
# x轴
line.add_xaxis(df.index.to_list())
# 每个y轴
line.add_yaxis("开盘价", df["open"].round(2).to_list())
line.add_yaxis("收盘价", df["close"].round(2).to_list())
# 图表配置
line.set_global_opts(
title_opts=opts.TitleOpts(title="百度股票2019年"),
tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross")
)
<pyecharts.charts.basic_charts.line.Line at 0x201bd51d088>
# 渲染数据
line.render_notebook()
本文使用 文章同步助手 同步
网友评论