簡體   English   中英

同一圖表上的Python繪圖條形圖和百分比折線圖

[英]Python plot bar chart and percentage line chart on same graph

我試圖在條形圖上繪制一條或多條線,以顯示一些不同的指標。 我聽說我應該使用ax.twinx(),但是我得到一個錯誤,說x和y必須具有相同的第一個維度,或者根據我嘗試的兩個東西讀取0L的不同錯誤。 這是我的代碼;

    x = df4['Date']
    y = df4['Rate']
    ax = df4[['Date','Qty']].set_index('Date') \
                            .plot(kind='bar',
                                  stacked=False,
                                  color = 'dodgerblue',
                                  figsize=(13,4),
                                  legend=True)
    ax.set_xlabel(r"$\rm \bf{Date}$",
                  fontsize=18, 
                  rotation = 0)
    ax.set_ylabel(r'$\cal \bf{Qty}$ ',fontsize=18, rotation = 90)

    ax2 = ax.twinx()
    ax2.plot(x, y, color = 'green', linestyle = '--', linewidth= 2.0)

注意; df4是一個分組的pandas數據幀。 不確定那是多么相關,只是為了以防萬一。

嘗試這個:

fig, ax = plt.subplots()
ax2 = ax.twinx()


df4[['Date','Qty']].set_index('Date') \
                   .plot(kind='bar',
                         ax=ax,
                         color = 'dodgerblue',
                         figsize=(13,4),
                         legend=False)

patches, labels = ax.get_legend_handles_labels()
ax.legend(patches, labels, loc='upper left')

ax.set_xlabel(r"$\rm \bf{Date}$", fontsize=18, rotation=0)
ax.set_ylabel(r'$\cal \bf{Qty}$ ',fontsize=18, rotation=90)

ax2.plot(range(len(df4)), df4['Rate'], 'green', label='Rate',
         linestyle = '--', linewidth=2.0)

patches, labels = ax2.get_legend_handles_labels()
ax2.legend(patches, labels, loc='upper right')

注意:如果您需要經過測試的解決方案,請提供樣本數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM