1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > pyecharts制作柱状图和折线图

pyecharts制作柱状图和折线图

时间:2024-05-07 15:23:16

相关推荐

pyecharts制作柱状图和折线图

图表

数据分析工作,离不开图表的展示。有时候表展示的数据更加清晰,有时候图绘制的形状更加直观。

最常用的办公工具Excel就是不错的选择,但是自动化比较难。

现在数据分析常用的编程语言是python,所以推荐一款用来绘制交互图的工具——pyecharts。

pyecharts将python和echarts结合在一起,使得数据分析的结果展示更加方便,更加美观。

数据准备

比如这次遇到这样的需求:分析一下数据与同期数据的对比分析工作,数据大概如下图,一列日期,一列数据。(案例数据用excel随机生成),数据截止到-06月份。

数据清洗

1、要求对比数据和同月份的数据,这就需要有两个月份列表,如下:

last_year_month = ['-01', '-02', '-03', '-04', '-05', '-06',]now_year_month = ['-01', '-02', '-03', '-04', '-05', '-06']# 下面代码可以自动生成上面的列表数据

但是这样不“智能”,每个月都需要手动加一下,虽然简单但是麻烦。

所以需要用代码自动生成两个对比的月份列表,我写的比较麻烦,应该有更简单的办法,我还没有找到。先这样写吧。

import datetimenow_year = datetime.datetime.now().yearnow_month = datetime.datetime.now().monthnow_year_month = []last_year_month = []for m in range(1,now_month):if m < 10:now_year_month.append("{0}-0{1}".format(str(now_year),str(m)))last_year_month.append("{0}-0{1}".format(str(now_year-1),str(m)))else:now_year_month.append("{0}-{1}".format(str(now_year),str(m)))last_year_month.append("{0}-{1}".format(str(now_year-1),str(m)))

2、对比的日期列表现在有了,但是图表应该如何展示?思来想去,最终决定——用月份做横坐标,数据作为纵坐标,将和的柱状图、折线图展示在图表中。

初期柱状图效果如下:

在pyecharts1.8.0以上版本,可以直接将柱状图转为折线图。

折线图效果如下:

其中,两条虚线表示对应的平均值。

版本V1制作过程

版本V1要求对比同期的数据即可。

具体步骤如下:

1、将“日期”拆分为“年份”和“月份”

df["年份"] = df["日期"].map(lambda x:str(int(x.split("-")[0]))+"年" if pd.notnull(x) else np.nan)df["月份"] = df["日期"].map(lambda x:str(int(x.split("-")[1]))+"月" if pd.notnull(x) else np.nan)

2、筛选对应的数据,为了保证数据按照时间排好序,需要用sort_values将数据排序

# 柱状图与折线图表示last_year_df = df[df["日期"].isin(last_year_month)].sort_values(by="日期")now_year_df = df[df["日期"].isin(now_year_month)].sort_values(by="日期")

3、用pyecharts画图

pyecharts图表教程有很多实例,只需要修改一下数据就可以完成很漂亮的交互式图表。

from pyecharts.charts import Line, Gridfrom pyecharts import options as opts# V1版本def bar_line(subtitle_text=None):x = now_year_df["月份"].astype(str).tolist()y1 = last_year_df['数据'].tolist()y2 = now_year_df['数据'].tolist()bar = (Bar(init_opts=opts.InitOpts(width="1000px", height="500px",bg_color="white")).add_xaxis(x).add_yaxis('数据', y1, color="rgba(51,75,92,1)",markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(name="均值",type_="average")]),).add_yaxis('数据', y2, color="rgba(194,53,49,1)",markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(name="均值",type_="average")]),).set_global_opts(title_opts=opts.TitleOpts(title='同期数据对比',subtitle=subtitle_text),toolbox_opts=opts.ToolboxOpts(),legend_opts=opts.LegendOpts(orient='vertical', pos_right='1%', pos_top='20%'),xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=0)),))grid = (Grid(init_opts=opts.InitOpts(width="1000px", height="500px",bg_color="white")).add(bar, grid_opts=opts.GridOpts(pos_bottom="15%")))return gridv1 = bar_line(subtitle_text="数据随机生成")v1.render_notebook()

版本V2制作过程

版本V2需要在图表上加上“阀值线”,以及展示同期下一个月的数据。比如:现在是-06,展示的数据要加上-07的数据。

1、加上同期下一个月的数据

import datetimenow_year = datetime.datetime.now().yearnow_month = datetime.datetime.now().monthnow_year_month = []last_year_month = []for m in range(1,now_month):if m < 10:now_year_month.append("{0}-0{1}".format(str(now_year),str(m)))last_year_month.append("{0}-0{1}".format(str(now_year-1),str(m)))else:now_year_month.append("{0}-{1}".format(str(now_year),str(m)))last_year_month.append("{0}-{1}".format(str(now_year-1),str(m)))# 将下一期的数据添加上去if 10<now_month<=11:last_year_month.append("{0}-{1}".format(str(now_year-1),str(now_month)))elif now_month == 12:passelse:last_year_month.append("{0}-0{1}".format(str(now_year-1),str(now_month)))

2、修改画图代码

# 版本1def bar_line(subtitle_text=None):# 横坐标用去年的月份x = last_year_df["月份"].astype(str).tolist()y1 = last_year_df['数据'].tolist()y2 = now_year_df['数据'].tolist()bar = (Bar(init_opts=opts.InitOpts(width="1000px", height="500px",bg_color="white")).add_xaxis(x).add_yaxis('数据', y1, color="rgba(51,75,92,1)",markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(name="均值",type_="average"),# 加上阀值线opts.MarkLineItem(name="阀值",y=3000),]),).add_yaxis('数据', y2, color="rgba(194,53,49,1)",markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(name="均值",type_="average"),# 加上阀值线opts.MarkLineItem(name="阀值",y=3000)]),).set_global_opts(title_opts=opts.TitleOpts(title='同期数据对比',subtitle=subtitle_text),toolbox_opts=opts.ToolboxOpts(),legend_opts=opts.LegendOpts(orient='vertical', pos_right='1%', pos_top='20%'),xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=0)),))grid = (Grid(init_opts=opts.InitOpts(width="1000px", height="500px",bg_color="white")).add(bar, grid_opts=opts.GridOpts(pos_bottom="15%")))return gridv2 = bar_line(subtitle_text="数据随机生成")v2.render_notebook()

效果图如下:

结论

如果你的工作也需要画图,那么pyecharts就是一个很不错的工具,pyecharts官网的教程十分详细,建议阅读方式:先看案例,如果需要修改内容在看详细教程。

更多好玩的内容,欢迎关注微信公众号“数据与编程之美”

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。