我试图用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开始的。

发布于 2019-04-07 00:01:38
问题是box()和plot()的工作方式不匹配- box()从x位置1开始,plot()取决于数据的索引(默认为从0开始)。只有8块地块,因为您指定了plt.xlim(-0.7, 8.7)后第9块就被切断了。有几种简单的方法可以解决这个问题,正如@Sheldore's answer所指出的,您可以显式地设置框图的位置。可以这样做的另一种方法是将failureRates数据的索引更改为在数据结构中从1开始,即
failureRates = pd.DataFrame(np.random.rand(9, 1), index=range(1, len(titles)+1))请注意,您不需要为问题MCVE指定xticks或xlim,但是您可能需要为完整的代码指定。

发布于 2019-04-06 21:35:15
您可以指定在x轴上的位置,您希望在其中有方框图。由于您有9个框,请使用以下方法生成下图
plotData.plot.box(ax=ax1, color=color, sym='+', positions=range(9))

https://stackoverflow.com/questions/55552051
复制相似问题