这是我的代码:
df = pd.DataFrame({'a': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
'b': [3, 4, 4, 4, 5, 4, 3, 4, 4, 5],
'c': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'd': [2, 3, 4, 4, 5, 5, 6, 7, 8, 10]},
index=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'])
df2 = pd.DataFrame({'Jan': [100,50,1/3*100,25,20,1/6*100,1/7*100,1/8*100,1/9*100,10],
'Feb': [0,50,1/3*100,25,20,1/6*100,1/7*100,1/8*100,1/9*100,10],
'Mar': [0,0,1/3*100,25,20,1/6*100,1/7*100,1/8*100,1/9*100,10],
'Apr': [0,0,0,25,20,1/6*100,1/7*100,1/8*100,1/9*100,10],
'May': [0,0,0,0,20,1/6*100,1/7*100,1/8*100,1/9*100,10],
'Jun': [0,0,0,0,0,1/6*100,1/7*100,1/8*100,1/9*100,10],
'Jul': [0,0,0,0,0,0,1/7*100,1/8*100,1/9*100,10],
'Aug': [0,0,0,0,0,0,0,1/8*100,1/9*100,10],
'Sep': [0,0,0,0,0,0,0,0,1/9*100,10],
'Oct': [0,0,0,0,0,0,0,0,0,10]},
index=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'])
ax = df.a.plot.line()
ax2 = df2.plot.bar(stacked=True)
df.a.plot.line(ax=ax2,secondary_y=range(0,11))
我希望组合图上的辅助y轴从0到10,以便将组合图中的线缩放到单独绘制时的线。我尝试使用secondary_y
字段,但是好像没有正确使用它。
答案 0 :(得分:2)
您可以通过使用ax2 = ax1.twinx()
在matplotlib.pyplot中执行此操作,然后在ax2上绘制堆积的条形图。
答案 1 :(得分:1)
尝试ax.twinx()
:
df.a.plot.line(ax=ax.twinx(), secondary_y=range(0, 11))
代替:
df.a.plot.line(ax=ax,secondary_y=range(0,11))
完整示例:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'a': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
'b': [3, 4, 4, 4, 5, 4, 3, 4, 4, 5],
'c': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'd': [2, 3, 4, 4, 5, 5, 6, 7, 8, 10]},
index=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'])
df2 = pd.DataFrame({'Jan': [100, 50, 1/3*100, 25, 20, 1/6*100, 1/7*100, 1/8*100, 1/9*100, 10],
'Feb': [0, 50, 1/3*100, 25, 20, 1/6*100, 1/7*100, 1/8*100, 1/9*100, 10],
'Mar': [0, 0, 1/3*100, 25, 20, 1/6*100, 1/7*100, 1/8*100, 1/9*100, 10],
'Apr': [0, 0, 0, 25, 20, 1/6*100, 1/7*100, 1/8*100, 1/9*100, 10],
'May': [0, 0, 0, 0, 20, 1/6*100, 1/7*100, 1/8*100, 1/9*100, 10],
'Jun': [0, 0, 0, 0, 0, 1/6*100, 1/7*100, 1/8*100, 1/9*100, 10],
'Jul': [0, 0, 0, 0, 0, 0, 1/7*100, 1/8*100, 1/9*100, 10],
'Aug': [0, 0, 0, 0, 0, 0, 0, 1/8*100, 1/9*100, 10],
'Sep': [0, 0, 0, 0, 0, 0, 0, 0, 1/9*100, 10],
'Oct': [0, 0, 0, 0, 0, 0, 0, 0, 0, 10]},
index=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'])
# Get axis
f = plt.figure(figsize=(5, 4), dpi=100)
ax = f.add_subplot(111)
df.a.plot.line(ax=ax, secondary_y=range(0, 11))
df2.plot.bar(stacked=True, ax=ax.twinx())
ax.set_zorder(ax.twinx().get_zorder()+1) # update zorder
ax.patch.set_visible(False) # hide the 'canvas'
# Fix size border bars
plt.autoscale(tight=True)
plt.show()
输出: