【问题标题】:Python matplotlib histogram plot Title with variablesPython matplotlib直方图带有变量的标题
【发布时间】:2018-04-18 02:55:15
【问题描述】:

我有一组如下所示的数据:

index   902.4  909.4   915.3
n       0.6    0.3     1.4
n.1     0.4    0.3     1.3
n.2     0.3    0.2     1.1
n.3     0.2    0.2     1.3
n.4     0.4    0.3     1.4
DCIS           0.3     1.6
DCIS.1  0.3    1.2
DCIS.2         1.1
DCIS.3  0.2    1.2
DCIS.4  0.2    1.3
DCIS.5  0.2    0.1     1.5
br_1    0.5    0.4     1.4
br_1.1         0.2     1.3
br_1.2  0.5    0.2     1.4
br_1.3  0.5    0.2     1.6
br_1.4         1.4

为列 [0] 使用常规 python 索引。下面是我在 Stackoverflow 成员的大量帮助下编写的代码:

nh = pd.ExcelFile(file)
df = pd.read_excel(nh)

df = df.set_index('Samples').transpose()

df = df.reset_index()

df_n = df.loc[df['index'].str.startswith('n')]
df_DCIS = df.loc[df['index'].str.startswith('DCIS')]
df_br1234 = df.loc[df['index'].str.startswith('br')]

#plt.tight_layout()

for i in range(1, df.shape[1]):
    plt.figure()
    df_n.iloc[:, i].hist(histtype='step', color='k', label='N')
    df_DCIS.iloc[:, i].hist(histtype='step', color='r', label='DCIS')
    df_br1234.iloc[:, i].hist(histtype='step', color='orange', label='IDC')
    plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), fancybox=True, shadow=True)
    plt.title("Histograms for " + df.columns[i], loc='center')

plt.show()

这会创建多个带有截止图例的图形(当图形由 pycharm 制作时,这并没有被切断)。但是,plt.title 给出了一条错误消息,指出 TypeError: must be str, not float。我知道不同数据帧的列是浮点数,当我输入 print(df.columns) 时,它说 dtype 是对象。有没有办法将浮动对象转换为 str?我尝试使用

plt.title("Histograms for " + df.columns[i].astype('str')) 

但它说浮动对象没有属性 astype。

【问题讨论】:

  • plt.title("Histograms for " + str(df.columns[i]))?
  • 您能否将其作为答案,以便我接受?我不确定这是否重要,但你解决我的问题太快了。

标签: python dataframe matplotlib


【解决方案1】:

试试

plt.title("Histograms for {0:.2f}".format(df.columns[i]))

大括号内的字符来自Format Specification Mini-Language。此示例格式化具有 2 个小数位的浮点数。如果您点击链接,您会看到许多其他选项。

【讨论】:

    【解决方案2】:

    你可以用这个:

    plt.title("Histograms for " + str(df.columns[i]))
    

    【讨论】:

      【解决方案3】:

      如果您不想将这些图连接在一起,我建议您完全避免使用subplots()。相反,用plt.show()分隔每个图:

      cols = ["902.4", "909.4", "915.3"]
      data = [{"df":df_n, "color":"k", "label":"N"},
              {"df":df_DCIS, "color":"r", "label":"DCIS"},
              {"df":df_br1234, "color":"orange", "label":"IDC"}]
      
      for col in cols:
          for dataset in data:
      
              dataset["df"][col].hist(histtype='step', 
                                      color=dataset["color"], 
                                      label=dataset["label"])
              plt.title(f"{dataset['label']} for {col}")
              plt.savefig(f"{dataset['label']}_for_{col}_plot.png")
              plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-16
        • 1970-01-01
        • 1970-01-01
        • 2014-04-15
        • 2016-12-18
        • 2017-06-29
        • 2019-02-13
        相关资源
        最近更新 更多