用两个Y轴从同一数据帧并排绘制两组序列

时间:2019-07-16 01:11:59

标签: python matplotlib plot

我有四个系列的数据框df;说'A', 'B', 'C', 'D' 我想将这些系列分布在两个具有相同y轴的地块上,非常类似于以下内容:enter image description here

我希望能够像现在一样独立控制每个地块:

import matplotlib.pyplot as plt  
ax = plt.gca()

# d is a dictionary from which dataframe is constructed
df = pd.DataFrame(data=d)

# to_plot (a function argument) is a dictionary of boolean values to decide what to plot, e.g.
to_plot = {'A':True,
           'B':True,
           'C':False,
           'D':True}

if to_plot['A']:
    pl = df['A'].plot(kind='bar', xticks=df.index, title=storage, ax=ax, color='deepskyblue', legend=True)

if to_plot['B']:
    pl = df['B'].plot(drawstyle='steps-post', xticks=df.index, title=storage, color='lightgreen',
                            linewidth=3, ax=ax, legend = True)
if to_plot['C']:
    pl = df['C'].plot(drawstyle='steps-post', xticks=df.index, title=storage, color='green',
                            linestyle='--', linewidth=2, ax=ax, legend=True)
if to_plot['D']:
    pl = df['D'].plot(drawstyle='steps-post', xticks=df.index, title=storage, color='orange',
                            linewidth=3, ax=ax, legend=True)

if to_plot['A'] or to_plot['B'] or to_plot['C'] or to_plot['D'] :
    plt.legend(loc='best')
    pl.set_xlabel("Time")
    pl.set_ylabel("Storage state(in %)")
    plt.show()

如您所见,某些图必须为bar,其他图必须为steps。除了决定独立的linewidthslinestyles之外,我还需要自由。除了我需要bar绘图和右边的steps绘图,两个y轴具有相同的y坐标的事实之外,我想保持一切不变。我首先制作了一个figure对象并向其中添加了轴:

fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 1, 1])

在上面的代码中添加这两行代码使绘图的某些部分超出了图形边界。更改[0.1, 0.1, 1, 1]中的值并使用figsize并没有帮助。最重要的是,我收到了以下警告:

UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect.
MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
  ax=fig.add_axes([0.1,0.1,1,1])
WARNING:matplotlib.legend:No handles with labels found to put in legend.

有没有一种方法可以使我的大部分代码保持不变并满足我的需要?

0 个答案:

没有答案