简体   繁体   English

Matplotlib:子图中的不同x轴标签

[英]Matplotlib: different x-axis labels in subplot

How do I get different x-axis labels in a subplot when generating it inside a for loop, as such; 在for循环内生成子图时,如何在子图中获得不同的x轴标签;

attributes = ["attr_with_2_categories", "attr_with_5_categories"]
target = 'Target'
for idx, variable in enumerate(attributes):

    plt.subplot(2, 1, idx+1)
    df_rate = DataSet[[target,variable]].groupby([variable]).mean()
    counts = DataSet[variable].value_counts()
    output = pd.concat((df_rate, counts), axis=1, sort=False)
    output.columns = ["DR", "Counts"]
    labels = np.unique(DataSet[variable])

    ax1 = output["Counts"].plot(kind='bar', width=0.5, color='skyblue', use_index=True)
    plt.ylabel("Count")
    ax1.set_xticklabels(labels, rotation = 45)
    ax2 = plt.twinx(ax1)
    ax2.plot(ax1.get_xticks(),output["DR"], linestyle='-', marker='o', linewidth=3.0)
    plt.ylabel("DR")
    plt.grid(False)
    plt.tight_layout()

plt.show()

The result here is two graphs but both graphs end up with the labels of the last graph that has 5 labels wile the first graph has only 2. 这里的结果是两个图,但是两个图都以最后一个图的标签结束,最后一个图的标签有5个标签,而第一个图只有2个。

You need to set the label to the axis objects. 您需要将标签设置为轴对象。 You might also need to tweak the spacing. 您可能还需要调整间距。 Below is an example: 下面是一个示例:

import matplotlib.pyplot as plt
import numpy as np
numrows = 3
numcols = 3
fig, ax = plt.subplots(ncols=numcols,nrows=numrows)
counter = 0
angles = np.linspace(0, 2*np.pi,100)
for i in range(numrows):
    for j in range(numcols):
        ax[i][j].plot(np.sin((i+1)*angles), np.cos((j+1)*angles))
        ax[i][j].set_xlabel('(%s,%s)'%(i+1,j+1))
        ax[i][j].set_aspect('equal')
plt.subplots_adjust(hspace=1.0)
plt.show()

subplots example with different x_axis labels 不同x_axis标签的子图示例

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

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