【问题标题】:change font size and bold of 'xticks' and 'Yticks' for subplots in matplotlib [duplicate]更改 matplotlib 中子图的“xticks”和“Yticks”的字体大小和粗体 [重复]
【发布时间】:2023-03-09 20:51:01
【问题描述】:

简而言之,我使用 python 中的 matplotlib 库绘制了这个带有三个子图的直方图。 我的问题是:如何将 'xticks' 和 'Yticks' 的字体大小增加到 24 并将其设为粗体。

代码

y12 = data_all_2[0]
y22= data_all_2[1]
y32= data_all_2[2]
bins =[0, 50, 100,150, 200,250]
names = ['legend_1', 'legend_2', 'legend_3', 'legend_4']
colors = ['b','c','r', 'g']

fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, sharex=True)
p1 = ax0.hist([y32[0:20], y32[20:34], y32[34:56], y32[56:68]],  bins, histtype='bar',   stacked=True, 
label=names,  rwidth=0.4, color = colors,edgecolor='black')
ax0.legend(loc=0, fontsize='x-large',prop={'size':8},)

p2 = ax1.hist([y12[0:20], y12[20:34], y12[34:56], y12[56:68]],  bins, histtype='bar',   stacked=True, 
 label=names,  rwidth=0.4, color = colors,edgecolor='black')
ax1.legend(loc=0, fontsize='x-large',prop={'size':8},)

p3 = ax2.hist([y22[0:20], y22[20:34], y22[34:56], y22[56:68]],  bins, histtype='bar',   stacked=True, 
label=names,  rwidth=0.4, color = colors,edgecolor='black')
ax2.legend(loc=0, fontsize='x-large',prop={'size':8},)
fig.subplots_adjust(hspace=0.6)

fig.text(0.5, 0.03,'bins' ,fontsize=14, fontweight='bold', ha='center', va='center' )
fig.text(0.05, 0.5, 'Y axis', fontsize=16, fontweight='bold', ha='center', 
 va='center',rotation='vertical')
# Add the rectangular patch to the Axes
xmin, xmax = 113,188
trans = transforms.blended_transform_factory(ax0.transData, fig.transFigure)
r = patches.Rectangle(xy=(xmin,0.1), width=xmax-xmin, height=0.750, transform=trans, fc='none', 
ec='m', lw=3, linestyle='dashed')
fig.add_artist(r)

plt.show()

输出

【问题讨论】:

  • 很遗憾,没有

标签: python matplotlib figure


【解决方案1】:

好吧,正如我在上面评论的那样,可以找到解决方案,例如已经在this question,所以我仍然认为这个问题应该作为重复关闭。

无论如何,试试这个例子:

font_props = {'family' : 'normal',
              'weight' : 'bold',
              'size'   : 24}
        
for a in [ax0,ax1,ax2]:
    for label in (a.get_xticklabels() + a.get_yticklabels()):
        label.set_font(font_props)

【讨论】:

  • 您的代码给出了关于 set_font (font_props) 的错误,[AttributeError: 'Text' object has no attribute 'set_font']。因此,正确如下:for a in [ax0, ax1, ax2]: for label in (a.get_xticklabels() + a.get_yticklabels()): label.set_fontsize(24) label.set_fontweight('bold') .这段代码适用于我。无需使用 font_props。
  • @MohsenAli 不确定您使用的是哪个 matplotlib.__version__,但 Text 对象 确实 具有 .set_font() 方法 in the latest versions of matplotlib
【解决方案2】:

答案是:

for a in [ax0, ax1, ax2]:
for label in (a.get_xticklabels() + a.get_yticklabels()):
    label.set_fontsize(24)
    label.set_fontweight('bold').

【讨论】:

    猜你喜欢
    • 2018-01-24
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2016-01-01
    • 2019-05-20
    • 2016-08-03
    • 1970-01-01
    相关资源
    最近更新 更多