我被困在一些感觉应该相对容易的事情上.我下面的代码是基于我正在研究的更大项目的示例.我没有理由发布所有细节,所以请接受我带来的数据结构.
基本上,我正在创建一个条形图,我只是想弄清楚如何在条形图上添加值标签(在条形图的中心,或者在它上面).一直在寻找网络上的样本,但没有成功实现我自己的代码.我相信解决方案要么是'text',要么是'annotate',但是我:a)不知道使用哪一个(一般来说,还没弄清楚何时使用哪个).b)无法看到要么呈现价值标签.非常感谢您的帮助,我的代码如下.提前致谢!
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.mpl_style', 'default')
%matplotlib inline
# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure. …Run Code Online (Sandbox Code Playgroud) 我写了一些代码来尝试解决这个问题:https: //stackoverflow.com/questions/39477748/how-to-annotate-bars-with-values-on-pandas-on-seaborn-factorplot-bar-plot
我使用了部分代码,可以在这里找到: matplotlib高级条形图
为什么图表这么小?代码只是告诉我从Pandas数据帧中获取准确性.
代码:
sns.set(style="white")
g = sns.factorplot(x="Stages", y="Accuracy", hue="Dataset", data=df, saturation = 5, size=4, aspect=2, kind="bar",
palette= myPalette, legend=False)
ax=g.ax
def annotateBars(row, ax=ax):
if row['Accuracy'] < 20:
color = 'white'
vertalign = 'bottom'
vertpad = 2
else:
color = 'black'
vertalign = 'top'
vertpad = -2
ax.text(row.name, row['Accuracy'] + vertpad, "{:.1f}%".format(row['Accuracy']),
zorder=10, rotation=90, color=color,
horizontalalignment='center',
verticalalignment=vertalign,
fontsize=12, weight='heavy')
junk = df.apply(annotateBars, ax=ax, axis=1)
Run Code Online (Sandbox Code Playgroud)
这是用于注释每个条形码的代码,但是......使用Pandas和Matplotlib.唯一的问题是,我不知道如何更改颜色和分组"x轴":(
df = df.set_index('Stages')
ax = df.plot.bar(title="Accuracy")
ax.set_ylim(0, 120)
for p in …Run Code Online (Sandbox Code Playgroud)