[英]Pandas & MatPlotLib: Plot a Bar Graph on Existing Scatter Plot or Vice Versa
我在一个窗口中绘制了一个折线图(使用 plot(x,y) 函数绘制),那么,是否可以在同一窗口中/上绘制条形图,以便对绘制的数据进行可视化分析?
为了响应Mattice ,重置索引或玩弄轴设置绘图参数将满足非整数请求。
请允许我演示:
import numpy as np
from pandas import DataFrame as DF
import calendar
import matplotlib.pyplot as plt
cells = {2006: [ 14.0223, 1.7171, 192.08],
2005: [ 5.1542, 0.6657, 28.5],
2004: [ 3.3514, 2.2503, 191.83],
2003: [ 9.1817, 0.4751, 143.83],
2002: [ 9.9821, 2.2136, 191.91],
2001: [ 13.701, 2.6296, 50],
1912: [ 8.5796, 4.4859, 191.91],
1911: [ 7.2977, 2.0956, 176.06],
1910: [ 3.9382, 3.1705, 112.19],
1909: [ 6.8692, 1.9548, 10.83]}
sprint = DF.from_dict(cells, orient="index", columns=['A', 'B', 'cost'])
sprint['total_data'] = sprint.A + sprint.B
sprint = DF.from_dict(cells, orient="index", columns=['A','B','cost'])
sprint['total_data'] = sprint.A + sprint.B
sprint.reset_index(inplace=True)
sprint['Month'] = sprint['index'].apply(lambda x: calendar.month_abbr[int(str(x)[-2:])])
sprint['Year'] = sprint['index'].apply(lambda x: 2000 + int(str(x)[:2]))
我将索引转换为字符串,但如果整数是唯一的,则同样适用于整数。 此方法将通过使用sprint.index = sprint.index.astype(str)
将索引简单地转换为字符串来sprint.index = sprint.index.astype(str)
。
sprint.index = sprint.Year.astype(str) + ' ' + sprint.Month
我尝试使用线条在一个图中打印线条,
sprint.plot(y=['A','B','total_data'], use_index=True)
但是,我发现我需要将条形图添加到散点图,因此不得不使用ax.plot
使用另一种方法,而不是 DataFrame 的内置方法。 从这里,我使用add_subplot
解析出两个图。 我需要解析 for 循环中的列以正确标记。
fig = plt.figure()
ax = fig.add_subplot(111)
for i in ['A','B','total_data']: ax.plot(sprint.index, sprint[i], label=i)
plt.legend(loc='upper right')
plt.xticks(rotation = 70)
然后,我能够添加带有自己的 y 轴和图例的辅助条形图,同时使用相同的 x 轴。
axB = ax.twinx()
axB.bar(sprint.index, sprint.cost, fill=False, label='cost')
plt.legend(loc='upper left')
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.