我被困在一些感觉应该相对容易的事情上.我下面的代码是基于我正在研究的更大项目的示例.我没有理由发布所有细节,所以请接受我带来的数据结构.
基本上,我正在创建一个条形图,我只是想弄清楚如何在条形图上添加值标签(在条形图的中心,或者在它上面).一直在寻找网络上的样本,但没有成功实现我自己的代码.我相信解决方案要么是'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) 我正试图在堆积条形图中"稳健地"将数据标签居中.下面给出一个简单的代码和结果.如您所见,数据标签并未真正居中于所有矩形.我错过了什么?
import numpy as np
import matplotlib.pyplot as plt
A = [45, 17, 47]
B = [91, 70, 72]
fig = plt.figure(facecolor="white")
ax = fig.add_subplot(1, 1, 1)
bar_width = 0.5
bar_l = np.arange(1, 4)
tick_pos = [i + (bar_width / 2) for i in bar_l]
ax1 = ax.bar(bar_l, A, width=bar_width, label="A", color="green")
ax2 = ax.bar(bar_l, B, bottom=A, width=bar_width, label="B", color="blue")
ax.set_ylabel("Count", fontsize=18)
ax.set_xlabel("Class", fontsize=18)
ax.legend(loc="best")
plt.xticks(tick_pos, ["C1", "C2", "C3"], fontsize=16)
plt.yticks(fontsize=16)
for r1, r2 in zip(ax1, ax2):
h1 = r1.get_height() …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个水平堆叠条形图,matplotlib但是我看不到如何使条形实际堆叠而不是从y轴开始.
这是我的测试代码.
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plot_chart(df, fig, ax)
ind = arange(df.shape[0])
ax.barh(ind, df['EndUse_91_1.0'], color='#FFFF00')
ax.barh(ind, df['EndUse_91_nan'], color='#FFFF00')
ax.barh(ind, df['EndUse_80_1.0'], color='#0070C0')
ax.barh(ind, df['EndUse_80_nan'], color='#0070C0')
plt.show()
Run Code Online (Sandbox Code Playgroud)
left在看到tcaswell的评论后编辑使用kwarg.
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plot_chart(df, fig, ax)
ind = arange(df.shape[0])
ax.barh(ind, df['EndUse_91_1.0'], color='#FFFF00')
lefts = df['EndUse_91_1.0']
ax.barh(ind, df['EndUse_91_nan'], color='#FFFF00', left=lefts)
lefts = lefts + df['EndUse_91_1.0']
ax.barh(ind, df['EndUse_80_1.0'], color='#0070C0', left=lefts)
lefts = lefts + df['EndUse_91_1.0']
ax.barh(ind, df['EndUse_80_nan'], color='#0070C0', left=lefts)
plt.show()
Run Code Online (Sandbox Code Playgroud)
这似乎是正确的方法,但如果没有特定条形的数据,它会失败,因为它试图添加nan一个然后返回的值nan.
我想将百分比值 - 除了计数 - 添加到我的熊猫条形图中。但是,我无法这样做。我的代码如下所示,到目前为止,我可以获得要显示的计数值。有人可以帮我在每个条形显示的计数值旁边/下方添加相对百分比值吗?
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')
import seaborn as sns
sns.set_style("white")
fig = plt.figure()
fig.set_figheight(5)
fig.set_figwidth(10)
ax = fig.add_subplot(111)
counts = [29227, 102492, 53269, 504028, 802994]
y_ax = ('A','B','C','D','E')
y_tick = np.arange(len(y_ax))
ax.barh(range(len(counts)), counts, align = "center", color = "tab:blue")
ax.set_yticks(y_tick)
ax.set_yticklabels(y_ax, size = 8)
#annotate bar plot with values
for i in ax.patches:
ax.text(i.get_width()+.09, i.get_y()+.3, str(round((i.get_width()), 1)), fontsize=8)
sns.despine()
plt.show();
Run Code Online (Sandbox Code Playgroud)
我的代码的输出如下所示。如何在显示的每个计数值旁边添加 % 值?
Matplotlib 3.4.2 有一个名为bar_label的函数,可以更轻松地向条形图添加数据标签。我有小数形式的数据(例如 0.9783),并且我想使用 bar_label 创建百分比形式的数据标签并四舍五入到最接近的单位(例如 98%)。
bar_label 有一个 fmt 变量,但我不确定要输入什么才能将数字格式化为四舍五入百分比。通常,我会使用 {:.0%}'.format(0.9786) 来达到 98%(根据本文档),但这种格式不适用于 bar_label。我可以使用另一种方法吗?
bar_label 代码将类似于: ax.bar_label(bars,fmt='[Not sure what to put here]')
我正在尝试在 Matplotlib 中使用新的 bar_label 选项,但无法找到在标签值后附加文本(例如 '%')的方法。以前,使用 ax.text 我可以使用 f 字符串,但我找不到通过 bar-label 方法使用 f 字符串的方法。
fig, ax = plt.subplots(1, 1, figsize=(12,8))
hbars = ax.barh(wash_needs.index, wash_needs.values, color='#2a87c8')
ax.tick_params(axis='x', rotation=0)
# previously I used this approach to add labels
#for i, v in enumerate(wash_needs):
# ax.text(v +3, i, str(f"{v/temp:.0%}"), color='black', ha='right', va='center')
ax.bar_label(hbars, fmt='%.2f', padding=3) # this adds a label but I can't find a way to append a '%' after the number
plt.show()
Run Code Online (Sandbox Code Playgroud) 嗨,我目前正在使用数据框绘制堆叠水平条形图。代码如下
new_data.plot.barh(stacked = True)
Run Code Online (Sandbox Code Playgroud)
我得到一个像下面这样的图表。
我该如何实现?任何帮助表示赞赏。谢谢
我一直在尝试用其值来注释堆积条形图的每个子金额,如上图所示(值不准确,只是一个示例)。
df.iloc[1:].T.plot(kind='bar', stacked=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)
链接的帖子与我的问题有些相似,但我不理解该答案中给出的代码,也没有给出任何解释。
我正在绘制某些类别中各个办公室的交叉表。我想放一张水平堆叠的条形图,在其中标记每个办公室及其值。
这是一些示例代码:
df = pd.DataFrame({'office1': pd.Series([1,np.nan,np.nan], index=['catA', 'catB', 'catC']),
'office2': pd.Series([np.nan,8,np.nan], index=['catA', 'catB', 'catC']),
'office3': pd.Series([12,np.nan,np.nan], index=['catA', 'catB', 'catC']),
'office4': pd.Series([np.nan,np.nan,3], index=['catA', 'catB', 'catC']),
'office5': pd.Series([np.nan,5,np.nan], index=['catA', 'catB', 'catC']),
'office6': pd.Series([np.nan,np.nan,7], index=['catA', 'catB', 'catC']),
'office7': pd.Series([3,np.nan,np.nan], index=['catA', 'catB', 'catC']),
'office8': pd.Series([np.nan,np.nan,11], index=['catA', 'catB', 'catC']),
'office9': pd.Series([np.nan,6,np.nan], index=['catA', 'catB', 'catC']),
})
ax = df.plot.barh(title="Office Breakdown by Category", legend=False, figsize=(10,7), stacked=True)
Run Code Online (Sandbox Code Playgroud)
这给了我一个很好的起点:
经过研究,我想到了以下代码,可以在“类别”轴上正确排列标签:
def annotateBars(row, ax=ax):
for col in row.index:
value = row[col]
if (str(value) != 'nan'):
ax.text(value/2, labeltonum(row.name), col+","+str(value))
def …Run Code Online (Sandbox Code Playgroud) 使用以下代码,我在 Matplotlib 的水平堆积条形图中添加了值标签:
import pandas
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
def sumzip(*items):
return [sum(values) for values in zip(*items)]
fig, ax = plt.subplots(figsize=(10,6))
N = 5
values1 = [130, 120, 170, 164, 155]
values2 = [120, 185, 162, 150, 153]
values3 = [100, 170, 160, 145, 150]
ind = np.arange(N) + .15
width = 0.3
rects1 = plt.barh(ind, values1, width, color='blue')
rects2 = plt.barh(ind, values2, width, left = sumzip(values1), color='green')
rects3 = plt.barh(ind, values3, width, left …Run Code Online (Sandbox Code Playgroud) 我有一个简单的数据框,用于存储调查结果。这些列是:
| Age | Income | Satisfaction |
Run Code Online (Sandbox Code Playgroud)
它们都包含1和之间的值5(分类)。我设法生成了一个堆积的条形图,该图显示Satisfaction了不同年龄人群的价值分布。代码是:
#create a random df
data = []
for i in range(500):
sample = {"age" : random.randint(0,5), "income" : random.randint(1,5), "satisfaction" : random.randint(1,5)}
data.append(sample)
df = pd.DataFrame(data)
#group by age
counter = df.groupby('age')['satisfaction'].value_counts().unstack()
#calculate the % for each age group
percentage_dist = 100 * counter.divide(counter.sum(axis = 1), axis = 0)
percentage_dist.plot.bar(stacked=True)
Run Code Online (Sandbox Code Playgroud)
但是,很难比较的green子集(百分比)Age-0是否高于中的子集(百分比)Age-2。因此,有一种方法可以将百分比添加到条形图的每个子部分的顶部。像这样,但对于每个单独的小节:

如何修改以下代码以显示条形图的每个条上的平均值以及不同的误差条?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("white")
a,b,c,d = [],[],[],[]
for i in range(1,5):
np.random.seed(i)
a.append(np.random.uniform(35,55))
b.append(np.random.uniform(40,70))
c.append(np.random.uniform(63,85))
d.append(np.random.uniform(59,80))
data_df =pd.DataFrame({'stages':[1,2,3,4],'S1':a,'S2':b,'S3':c,'S4':d})
print("Delay:")
display(data_df)
S1 S2 S3 S4
0 43.340440 61.609735 63.002516 65.348984
1 43.719898 40.777787 75.092575 68.141770
2 46.015958 61.244435 69.399904 69.727380
3 54.340597 56.416967 84.399056 74.011136
meansd_df=data_df.describe().loc[['mean', 'std'],:].drop('stages', axis = 1)
display(meansd_df)
sns.set()
sns.set_style('darkgrid',{"axes.facecolor": ".92"}) # (1)
sns.set_context('notebook')
fig, ax = plt.subplots(figsize = (8,6))
x = meansd_df.columns
y …Run Code Online (Sandbox Code Playgroud) 我正在尝试绘制一个如下所示的条形图,我不确定如何在每列顶部设置百分比值,并在右侧设置图例。我的代码片段如下。它正在工作,但是缺少百分比值和图例。
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
objects = ('18-25', '26-30', '31-40', '40-50')
y_pos = np.arange(len(objects))
performance = [13, 18, 16, 3]
width = 0.35 # the width of the bars
plt.bar(y_pos, performance, align='center', alpha=0.5, color=('red', 'green', 'blue', 'yellow'))
plt.xticks(y_pos, objects)
plt.ylabel('%User', fontsize=16)
plt.title('Age of Respondents', fontsize=20)
width = 0.35
plt.show()
Run Code Online (Sandbox Code Playgroud)
matplotlib ×13
python ×13
pandas ×7
bar-chart ×6
format ×1
percentage ×1
python-2.7 ×1
python-3.x ×1
seaborn ×1