我被困在一些感觉应该相对容易的事情上.我下面的代码是基于我正在研究的更大项目的示例.我没有理由发布所有细节,所以请接受我带来的数据结构.
基本上,我正在创建一个条形图,我只是想弄清楚如何在条形图上添加值标签(在条形图的中心,或者在它上面).一直在寻找网络上的样本,但没有成功实现我自己的代码.我相信解决方案要么是'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) 我试图在matplotlib中复制以下图像,似乎是我唯一的选择.虽然看起来你不能堆叠barh图,所以我不知道该怎么做
如果你知道一个更好的python库来绘制这种东西,请告诉我.
这就是我可以想到的一切:
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
people = ('A','B','C','D','E','F','G','H')
y_pos = np.arange(len(people))
bottomdata = 3 + 10 * np.random.rand(len(people))
topdata = 3 + 10 * np.random.rand(len(people))
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)
ax.barh(y_pos, bottomdata,color='r',align='center')
ax.barh(y_pos, topdata,color='g',align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel('Distance')
plt.show()
Run Code Online (Sandbox Code Playgroud)
然后我必须使用ax.text单独添加标签,这将是乏味的.理想情况下,我只想指定要插入的部分的宽度,然后用我选择的字符串更新该部分的中心.外面的标签(例如3800)我可以稍后添加自己,它主要是条形部分本身的标签,并以一种很好的方式创建这个堆叠的方法我遇到了问题.你甚至可以用任何方式指定"距离"即颜色范围吗?
我正试图在堆积条形图中"稳健地"将数据标签居中.下面给出一个简单的代码和结果.如您所见,数据标签并未真正居中于所有矩形.我错过了什么?
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) 我想将百分比值 - 除了计数 - 添加到我的熊猫条形图中。但是,我无法这样做。我的代码如下所示,到目前为止,我可以获得要显示的计数值。有人可以帮我在每个条形显示的计数值旁边/下方添加相对百分比值吗?
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)
我的代码的输出如下所示。如何在显示的每个计数值旁边添加 % 值?
我遇到了一个关于 Python 中 matplotlib 的棘手问题。我想创建一个包含多个代码的分组条形图,但图表出错了。您能给我一些建议吗?代码如下。
import numpy as np
import pandas as pd
file="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DV0101EN/labs/coursera/Topic_Survey_Assignment.csv"
df=pd.read_csv(file,index_col=0)
df.sort_values(by=['Very interested'], axis=0,ascending=False,inplace=True)
df['Very interested']=df['Very interested']/2233
df['Somewhat interested']=df['Somewhat interested']/2233
df['Not interested']=df['Not interested']/2233
df
df_chart=df.round(2)
df_chart
labels=['Data Analysis/Statistics','Machine Learning','Data Visualization',
'Big Data (Spark/Hadoop)','Deep Learning','Data Journalism']
very_interested=df_chart['Very interested']
somewhat_interested=df_chart['Somewhat interested']
not_interested=df_chart['Not interested']
x=np.arange(len(labels))
w=0.8
fig,ax=plt.subplots(figsize=(20,8))
rects1=ax.bar(x-w,very_interested,w,label='Very interested',color='#5cb85c')
rects2=ax.bar(x,somewhat_interested,w,label='Somewhat interested',color='#5bc0de')
rects3=ax.bar(x+w,not_interested,w,label='Not interested',color='#d9534f')
ax.set_ylabel('Percentage',fontsize=14)
ax.set_title("The percentage of the respondents' interest in the different data science Area",
fontsize=16)
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend(fontsize=14)
def autolabel(rects):
"""Attach a text label above each bar …
Run Code Online (Sandbox Code Playgroud) 以下是熊猫数据框和从中生成的条形图:
colors_list = ['#5cb85c','#5bc0de','#d9534f']
result.plot(kind='bar',figsize=(15,4),width = 0.8,color = colors_list,edgecolor=None)
plt.legend(labels=result.columns,fontsize= 14)
plt.title("Percentage of Respondents' Interest in Data Science Areas",fontsize= 16)
plt.xticks(fontsize=14)
for spine in plt.gca().spines.values():
spine.set_visible(False)
plt.yticks([])
Run Code Online (Sandbox Code Playgroud)
我需要在相应栏上方显示相应主题的每个兴趣类别的百分比。我可以创建带有百分比的列表,但是我不知道如何将其添加到相应栏的顶部。
我一直在尝试用其值来注释堆积条形图的每个子金额,如上图所示(值不准确,只是一个示例)。
df.iloc[1:].T.plot(kind='bar', stacked=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)
链接的帖子与我的问题有些相似,但我不理解该答案中给出的代码,也没有给出任何解释。
如何修改以下代码以显示条形图的每个条上的平均值以及不同的误差条?
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)