简体   繁体   English

matplotlib y 轴标签随着字体大小的变化而消失

[英]matplotlib y axis labels disappearing with fontsize change

I have the following code to plot the contents of a dataframe.我有以下代码来绘制数据框的内容。

Using pandas and matplotlib:使用熊猫和 matplotlib:

thedata = {'2013':[0.0,0.0]
          ,'2014':[0.0,0.0]
          ,'2015':[0.0,0.0]
          ,'2016':[1,0.0]
          ,'2017':[0.0,0.0]
          ,'2018':[1,0.0]}

my_df = pd.DataFrame(thedata, index=['Green cars','Red cars'])

    plt.figure(figsize=(7,3))
    my_ax = plt.gca()
    my_ax.clear()
    my_ax.yaxis.set_major_locator(MaxNLocator(integer=True))

    my_df.transpose().plot(kind='bar'
                , stacked=True  
                , ax=my_ax
                ).grid(True,'major','y')

    my_ax.legend(loc=9, bbox_to_anchor=(0.5, -0.1), frameon=False, ncol=2, fontsize=12 )
    plt.title('All the cars', fontsize = 12 )
    my_ax.set_xticklabels(my_ax.get_xticklabels(),rotation='horizontal', fontsize=12)
#     my_ax.set_yticklabels(my_ax.get_yticklabels(),fontsize=12)

数据框和输出

The last line is commented out in order to get the output displayed.最后一行被注释掉,以便显示输出。 I want to increase the font size of the y axis labels to be the same as the x, but when i un-comment that line and run it, the y axis labels just disappear and nothing is displayed there.我想将 y 轴标签的字体大小增加到与 x 相同,但是当我取消注释该行并运行它时,y 轴标签就会消失并且没有显示任何内容。

Why is this happening and how do I fix it?为什么会发生这种情况,我该如何解决?

Edit: - create the dataframe;编辑: - 创建数据框; pandas 0.23.0, matplotlib 2.2.2熊猫 0.23.0,matplotlib 2.2.2

The problem you face here is that the ticklabels are not actually defined before the figure is drawn.您在这里面临的问题是在绘制图形之前实际上并未定义刻度标签。

import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

fig, ax = plt.subplots()
ax.plot([1,3,4,2])
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.set_xticklabels(ax.get_xticklabels(),fontsize=12)
plt.show()

在此处输入图片说明

You may draw the figure, before accessing those labels在访问这些标签之前,您可以绘制图形

fig, ax = plt.subplots()
ax.plot([1,3,4,2])
ax.xaxis.set_major_locator(MaxNLocator(integer=True))

fig.canvas.draw()
ax.set_xticklabels(ax.get_xticklabels(),fontsize=12)
plt.show()

在此处输入图片说明

However, in order to change the fontsize of the ticklabels, one would rather use然而,为了改变刻度标签的字体大小,人们宁愿使用

ax.tick_params(axis="x", labelsize=12)

or set the property to the labels, without actually setting the labels' content.或者将属性设置为标签,而不实际设置标签的内容。 Eg via setp例如通过setp

plt.setp(ax.get_xticklabels(), fontsize=12)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM