多个绘图栏图例

2024-04-30 05:59:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用pandas数据帧的不同列创建的多个条形图。在

fig1 = plt.figure()
ypos = np.arange(len(dframe))

colorscheme = seaborn.color_palette(n_colors=4)

accuracyFig = fig1.add_subplot(221)
accuracyFig.bar(ypos,dframe['accuracy'], align = 'center', color=colorscheme)
accuracyFig.set_xticks([0,1,2,3])
accuracyFig.set_ylim([0.5,1])

sensitivityFig = fig1.add_subplot(222)
sensitivityFig.bar(ypos, dframe['sensitivity'], align = 'center',color=colorscheme )
sensitivityFig.set_xticks([0,1,2,3])
sensitivityFig.set_ylim([0.5,1])

specificityFig = fig1.add_subplot(223)
specificityFig.bar(ypos, dframe['specificity'], align = 'center', color=colorscheme)
specificityFig.set_xticks([0,1,2,3])
specificityFig.set_ylim([0.5,1])

precisionFig = fig1.add_subplot(224)
precisionFig.bar(ypos, dframe['precision'], align = 'center', color=colorscheme)
precisionFig.set_xticks([0,1,2,3])
precisionFig.set_ylim([0.5,1])

其中dframe是具有整数值的pandas数据帧。这将输出下图enter image description here。在

每个颜色对应于一个分类器模型-perceptron,C2,C3 and C4,该模型存储在pandasdframe['name']

现在我想为整个人物绘制一个单独的传说。我试过以下方法

^{pr2}$

任何关于如何绘制单个图例并将其放置在2列中的图形的帮助。在

但它给出了如下的enter image description here。在

这是我的数据帧

                     name        accuracy     sensitivity     specificity       precision
0              perceptron  0.820182164169  0.852518881235  0.755172413793  0.875007098643
1  DecisionTreeClassifier             1.0             1.0             1.0             1.0
2    ExtraTreesClassifier             1.0             1.0             1.0             1.0
3  RandomForestClassifier  0.999796774253  0.999889340748  0.999610678532  0.999806362379

Tags: addbarcolorcentersetaligncolorschemedframe
3条回答

我修改了代码如下

fig1 = plt.figure()

A = list(range(1,len(dframe)+1))
labels = dframe['name'].tolist()

colorscheme = sns.color_palette(n_colors=len(dframe))


accuracyFig = fig1.add_subplot(221)
for i in range(0,len(A)):
    accuracyFig.bar(A[i],dframe['accuracy'][i+1], align = 'center',label = labels[i], color = colorscheme[i])
accuracyFig.set_xticks([])
accuracyFig.set_ylim([0.5,1])
accuracyFig.set_title('Accuracy')

sensitivityFig = fig1.add_subplot(222)
for i in range(0,len(A)):
    sensitivityFig.bar(A[i],dframe['sensitivity'][i+1], align = 'center',label = labels[i], color = colorscheme[i])
sensitivityFig.set_xticks([])
sensitivityFig.set_ylim([0.5,1])
sensitivityFig.set_title('Sensitivity')

specificityFig = fig1.add_subplot(223)
for i in range(0,len(A)):
    specificityFig.bar(A[i],dframe['specificity'][i+1], align = 'center',label = labels[i], color = colorscheme[i])
specificityFig.set_xticks([])
specificityFig.set_ylim([0.5,1])
specificityFig.set_title('Specificity')

precisionFig = fig1.add_subplot(224)
for i in range(0,len(A)):
    precisionFig.bar(A[i],dframe['precision'][i+1], align = 'center',label = labels[i], color = colorscheme[i])
precisionFig.set_xticks([])
precisionFig.set_ylim([0.5,1])
precisionFig.set_title('Precision')

# Plot the legend:

plt.legend(loc = 'lower center',bbox_to_anchor = (0,-0.05,1,2), ncol=2,
        bbox_transform = plt.gcf().transFigure)

plt.show()

我没有使用固定长度的标签,而是直接从数据帧中复制它们,这样就可以了。在

我做了一些更新,并将参数(n_cols = 2)添加到legend函数中,这样我的输出图如下所示 enter image description here

谢谢@Charles Morris的帮助

可以使用以下命令将图例移动到图表中需要的位置。在

绘制条形图时需要添加标签。我改变了你描绘传奇的主线。在

我添加了一些伪标签,在您的代码中,您可以通过执行labels = list(df)来获得标签,为您提供数据帧中的列名列表。在

import matplotlib.pyplot as plt

colorscheme = ['r','b','c','y']
fig1 = plt.figure()
accuracyFig = fig1.add_subplot(221)
A =[1,2,3,4]
B = [4,3,2,1]
labels = ['perceptron','C2','C3','C4']
for i in range(0,len(A)):
    accuracyFig.bar(A[i],B[i], align = 'center',label = labels[i], color = colorscheme[i])

accuracyFig1 = fig1.add_subplot(223)
A =[1,2,3,4]
B = [4,3,2,1]
labels = ['perceptron','C2','C3','C4']
for i in range(0,len(A)):
    accuracyFig1.bar(A[i],B[i], align = 'center',label = labels[i], color = colorscheme[i])

accuracyFig2 = fig1.add_subplot(222)
A =[1,2,3,4]
B = [4,3,2,1]
labels = ['perceptron','C2','C3','C4']
for i in range(0,len(A)):
    accuracyFig2.bar(A[i],B[i], align = 'center',label = labels[i], color = colorscheme[i])

accuracyFig3 = fig1.add_subplot(224)
A =[1,2,3,4]
B = [4,3,2,1]
labels = ['perceptron','C2','C3','C4']
for i in range(0,len(A)):
    accuracyFig3.bar(A[i],B[i], align = 'center',label = labels[i], color = colorscheme[i])

# Plot the legend:
# You don't want to plot to any particular axis, instead to a general plot.

plt.legend(loc = 'lower center',bbox_to_anchor = (0,-0.3,1,1),
        bbox_transform = plt.gcf().transFigure)
plt.show()

图例图来源:

How to create custom legend in matplotlib based on the value of the barplot?how do I make a single legend for many subplots with matplotlib?How to put the legend out of the plot

enter image description here

更新:意外删除了我的评论:在legend()中添加ncol = 2将得到您想要的对称分割行为。在

好吧,首先,您的表不是一个整齐的格式(参见这里:http://vita.had.co.nz/papers/tidy-data.pdf)。在

使您的表格保持整洁(或长)格式有一个巨大的优势,即使用seaborn绘图变得非常容易(除其他优点外):

df # yours
                     name        accuracy     sensitivity     specificity       precision
0              perceptron  0.820182164169  0.852518881235  0.755172413793  0.875007098643
1  DecisionTreeClassifier             1.0             1.0             1.0             1.0
2    ExtraTreesClassifier             1.0             1.0             1.0             1.0
3  RandomForestClassifier  0.999796774253  0.999889340748  0.999610678532  0.999806362379

将其转换为长格式(或整齐):

^{pr2}$

然后,只需在一行+2行中绘制您想要的内容,以使其更清晰:

g = sns.factorplot(data=df2,
                   kind="bar",
                   col="variable", # you have 1 plot per variable, forming 1 line and 4 columns (4 different variables)
                   x="name", # in each plot the x-axis will be the name
                   y="value", # the height of the bar
                   col_wrap=2) # you actually want your line of plots to contain 2 plots maximum 
g.set_xticklabels(rotation=90) # rotate the labels so they don't overlap
plt.tight_layout() # fit everything into the figure

multiple barplot

高温

相关问题 更多 >