我有一個如下所示的 Pandas DataFrame:counts = pd.DataFrame({'Pair A': {8: 4, 9: 1, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0}, 'Pair B': {8: 4, 9: 2, 10: 1, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0}, 'Pair C': {8: 3, 9: 2, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1}, 'Pair D': {8: 2, 9: 1, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0}})我只是使用以下代碼使用 DataFrame 的一部分創建一個簡單的圖:plt.figure()sns.set_palette("pastel")temp = pd.DataFrame(counts).drop([0,1,2,3,4,5,6], axis='index')temp.index = temp.index + 1temp.plot()sns.set_style('ticks')plt.ylabel('title')plt.xlabel('xlabel')plt.title('title')plt.xticks(range(len(temp.index)), temp.index, rotation=45)plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))sns.despine(offset=10, trim=True)plt.xticks(rotation=45)但它會產生如下所示的圖像:如何將繪圖居中在 x 軸上?
2 回答

紫衣仙女
TA貢獻1839條經驗 獲得超15個贊
這似乎是:
plt.xticks(range(len(temp.index)), temp.index, rotation=45)
導致問題,如果替換為:
plt.xticks(temp.index, temp.index, rotation=45)
一切都按預期工作。

精慕HU
TA貢獻1845條經驗 獲得超8個贊
當您調用plt.xticks
, 并提供 2 個位置參數時,第一個參數變為locs
標簽將出現的 x 值,第二個變為labels
刻度標簽值。因此,plt.xticks(range(len(temp.index)), temp.index, rotation=45)
您在位置 0、1、2、3.... 處繪制 x 刻度標簽,而您的數據在不同的范圍內(8、9、10....)。
因此,如果您想自定義標簽,您可以更改label
部分,例如plt.xticks(temp.index, ['x%s'% v for v in temp.index], rotation=45)
.
添加回答
舉報
0/150
提交
取消