matplotlib 旋转后x轴记号标签分布不均

vjrehmav  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(195)

在该棒棒糖/干图中,显示了每个参与者的两个类别(左/右)的指数值,在旋转标签后,x标签相对于x刻度不均匀分布:

旋转前:

x-labels are not legible but centered around the x-tick

旋转后:

x-labels are legible but the first 7 labels are centered slightly right from the x-tick, whereas the last 16 labels are centered slightly left from the tick
无线:plt.xticks(rotation = 'vertical', ha = 'right', rotation_mode='anchor')

数据:

df_LR = pd.read_csv("Index_for_stats_LeftRight_merge.csv")
pandas dataframe with separate columns for left and right

剧情:

来自https://www.python-graph-gallery.com/184-lollipop-plot-with-2-groups的代码。它通过结合plt.vlines和plt. scatter创建棒棒糖图。

f, ax = plt.subplots(figsize=(10, 6))

# Reorder dataframe following the values of the first value:
df_LR = df_LR.sort_values(by='index_right')
my_range=range(1,len(df_LR.index)+1)
 
# The vertical plot is made using the vline function
plt.vlines(x=my_range, ymin=df_LR['index_left'], ymax=df_LR['index_right'], color='grey', alpha=0.4)
plt.scatter(my_range, df_LR['index_left'], color='#E68900', alpha=1, label='left')
plt.scatter(my_range, df_LR['index_right'], color='seagreen', alpha=1, label='right')
plt.legend()
 
# Add title and axis names
plt.xticks(rotation = 'vertical', ha = 'right', rotation_mode='anchor')
plt.xticks(my_range, df_LR['subject ID'])
plt.title("Index: left-right differences per participant", loc='left')
plt.ylabel('Index')
plt.xlabel('')

# Show graph
plt.show()

我试着调整指定旋转的xticks行(将“vertical”交换为float,将ha =“right”交换为“left”),但这些变化仅在x轴上显示的前7个主题中可见。这就像是从11号线开始的事情被打乱了。
任何关于如何解决这个问题的想法将不胜感激!

n8ghc7c1

n8ghc7c11#

首先进行更换,然后才旋转(即交换这两条线的位置):

plt.xticks(my_range, df_LR['subject ID'])
plt.xticks(rotation = 'vertical', ha = 'right', rotation_mode='anchor')

进一步说明:
我看到您首先通过f, ax = plt.subplots(figsize=(10, 6))创建了一个图形,然后使用pyplot接口继续。您混合了两种可能的接口。如果你打算经常使用Matplotlib,你可能会对以下阅读材料感兴趣:
https://matplotlib.org/matplotblog/posts/pyplot-vs-object-oriented-interface/
结合Matplotlib和Pandas时理解fig、ax和plt
What is the difference between drawing plots using plot, axes or figure in matplotlib?

相关问题