簡體   English   中英

Matplotlib:在未對齊的雙 y 軸繪圖上繪圖

[英]Matplotlib: Plot on double y-axis plot misaligned

我正在嘗試使用 matplotlib 將兩個數據集繪制成一個圖。 兩個圖之一在 x 軸上錯位了 1。 這個 MWE 幾乎總結了這個問題。 我需要調整什么才能使箱線圖進一步向左移動?

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

titles = ["nlnd", "nlmd", "nlhd", "mlnd", "mlmd", "mlhd", "hlnd", "hlmd", "hlhd"]
plotData = pd.DataFrame(np.random.rand(25, 9), columns=titles)
failureRates = pd.DataFrame(np.random.rand(9, 1), index=titles)
color = {'boxes': 'DarkGreen', 'whiskers': 'DarkOrange', 'medians': 'DarkBlue', 
         'caps': 'Gray'}
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
plotData.plot.box(ax=ax1, color=color, sym='+')
failureRates.plot(ax=ax2, color='b', legend=False)
ax1.set_ylabel('Seconds')
ax2.set_ylabel('Failure Rate in %')
plt.xlim(-0.7, 8.7)
ax1.set_xticks(range(len(titles)))
ax1.set_xticklabels(titles)
fig.tight_layout()
fig.show()

實際結果。 請注意,它只有 8 個箱線圖而不是 9 個,並且它們從索引 1 開始。

MWE圖片

您可以指定要在 x 軸上放置箱線圖的位置。 由於您有 9 個盒子,請使用以下生成下圖的方法

plotData.plot.box(ax=ax1, color=color, sym='+', positions=range(9))

在此處輸入圖片說明

問題是box()plot()工作方式不匹配 - box()從 x 位置 1 開始, plot()取決於數據box()的索引(默認為從 0 開始)。 由於您指定了plt.xlim(-0.7, 8.7)因此第 9 個圖被截斷,因此只有 8 個圖。 有幾種簡單的方法可以解決這個問題,正如@Sheldore 的回答所示,您可以明確設置箱線圖的位置。 另一種方法是在failureRates數據幀時將failureRates數據幀的索引更改為從 1 開始,即

failureRates = pd.DataFrame(np.random.rand(9, 1), index=range(1, len(titles)+1))

請注意,您不需要為問題 MCVE 指定xticksxlim ,但您可能需要為您的完整代碼指定。

在此處輸入圖片說明

暫無
暫無

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

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