带变量的Python matplotlib直方图打印标题
我有一组数据,如下所示:带变量的Python matplotlib直方图打印标题,python,dataframe,matplotlib,Python,Dataframe,Matplotlib,我有一组数据,如下所示: 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
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:必须是str,而不是float。我知道不同数据帧的列是浮点数,当我键入print(df.columns)时,它会说dtype是object。有没有办法将float对象转换为str?我试着用
plt.title("Histograms for " + df.columns[i].astype('str'))
但它说float对象没有属性astype 试试看
plt.title("Histograms for {0:.2f}".format(df.columns[i]))
花括号内的字符来自。此示例使用小数点后两位设置浮点格式。如果您点击该链接,您将看到许多其他选项。试试看
plt.title("Histograms for {0:.2f}".format(df.columns[i]))
花括号内的字符来自。此示例使用小数点后两位设置浮点格式。如果您点击该链接,您将看到许多其他选项。您可以使用以下选项:
plt.title("Histograms for " + str(df.columns[i]))
您可以使用以下选项:
plt.title("Histograms for " + str(df.columns[i]))
如果您不想将绘图连接在一起,我建议您完全避免
子绘图()。相反,用plt.show()分隔每个绘图:
如果您不想将绘图连接在一起,我建议您完全避免子绘图()。相反,用plt.show()分隔每个绘图:
plt.title(“柱状图”+str(df.columns[i]))
?你能给我一个答案让我接受吗?我不确定这是否很重要,但你太快解决了我的问题。plt.title(“柱状图”+str(df.columns[I]))
?你能回答这个问题让我接受吗?我不确定这是否重要,但你太快解决了我的问题。