首页 > 解决方案 > 如何在该图的直方图上自定义标题和轴标签?

问题描述

我想在直方图 y 轴的右侧添加标题“幅度”。还想在框架内添加散点图标题。怎么做?我可以用单线添加这些功能吗?

我的代码和输出图如下

# definitions for the axes
left, width = 0.1, 0.65 #width : width of the main plot(Xaxis length)
bottom, height = 0.1, 0.4 #height : height of the main plot(Yaxis length)
spacing = 0.010 # gap between the plots


rect_scatter = [left, bottom, width, height]

rect_histx = [left, bottom + height + spacing, width, 0.2]

rect_histy = [left + width + spacing, bottom, 0.2, height]

# start with a square Figure
fig = plt.figure(figsize=(8, 10))

ax = fig.add_axes(rect_scatter)
ax_histx = fig.add_axes(rect_histx, sharex=ax)
ax_histy = fig.add_axes(rect_histy, sharey=ax)

# use the previously defined function
scatter_hist(df.YearDeci,df.Magnitude,ax,ax_histx,ax_histy,binx,biny)

ax.set_xticks(np.arange(t1,t2,5))
extraticks=[2018]
ax.set_xticks(list(ax.get_xticks()) + extraticks)

plt.show()
#######################################################
def scatter_hist(x, y,ax,ax_histx,ax_histy,binx,biny):
    # no labels
    ax_histx.tick_params(axis="x", labelbottom=False)
    ax_histx.set(ylabel='Number of events',title='Time',facecolor='lightgray')
    
    ax_histy.tick_params(axis="y", labelleft=False)
    ax_histy.set(xlabel='Number of events',facecolor='lightgray')
    ax_histy.yaxis.set_label_position("right")

    # the scatter plot:
    ax.scatter(x, y,  facecolor='yellow', alpha=0.75,edgecolor='black',linewidth=0.5,s=30)
    plt.setp(ax.get_xticklabels(), rotation = 90,fontsize=10)
    ax.set(xlabel='Time',ylabel='Number of events',facecolor='lightgray')


    # now determine nice limits by hand:

    ax_histx.hist(x, bins=binx, density=False, facecolor='r', alpha=0.75,edgecolor='black',linewidth=0.5)
    ax_histy.hist(y, bins=biny,  density=False, facecolor='r', alpha=0.75,edgecolor='black',linewidth=0.5,orientation='horizontal')
   
    

在此处输入图像描述

标签: python-3.xmatplotlibhistogram

解决方案


而不是标题,只需向该轴添加文本。您可以随意旋转和定位它。 是一个例子。

ax_histy.text(left + width + spacing + 0.2 + 0.1, bottom + 0.5*height, 'test',
    horizontalalignment='center',
    verticalalignment='center',
    rotation=270,
    fontsize=12,
    transform=ax_histy.transAxes)

似乎适用于您的情况。玩弄定位和大小以获得您想要的方式。

在此处输入图像描述


推荐阅读