Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何绘制和注释分组条形图_Python_Pandas_Matplotlib_Bar Chart - Fatal编程技术网

Python 如何绘制和注释分组条形图

Python 如何绘制和注释分组条形图,python,pandas,matplotlib,bar-chart,Python,Pandas,Matplotlib,Bar Chart,我遇到了一个关于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.

我遇到了一个关于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 in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 3, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')


autolabel(rects1)
autolabel(rects2)
autolabel(rects3)

fig.tight_layout()

plt.show()
这个代码模块的输出真是一团糟。但我所期望的应该像图中的条形图。你能告诉我代码中哪一点不正确吗

导入和数据帧
将熊猫作为pd导入
将matplotlib.pyplot作为plt导入
#给定以下代码来创建数据帧
文件=”https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DV0101EN/labs/coursera/Topic_Survey_Assignment.csv"
df=pd.read\u csv(文件,索引\u col=0)
排序_值(按=['Very interest'],轴=0,升序=False,原地=True)
df['Very interest']=df['Very interest']/2233
df['Social Interest']=df['Social Interest']/2233
df['notinterest']=df['notinterest']/2233
使用自matplotlib v3.4.2以来的

  • 使用
  • 有关其他格式选项,请参见页面。
    • 一些格式化可以使用
      fmt
      参数完成,但更复杂的格式化应该使用
      labels
      参数完成,如底部演示示例和中所示
#你的颜色
颜色=['#5cb85c'、'#5bc0de'、'#d9534f']
#带注释的绘图可能更容易
p1=df.plot.bar(color=colors,figsize=(20,8),ylabel='Percentage',title=“受访者对不同数据科学领域感兴趣的百分比”)
p1.setxticklabels(p1.getxticklabels(),旋转=0)
对于p1.1容器中的p:
p1.条形图标签(p,fmt='%.2f',标签类型='edge')

注释资源-来自
matplotlib v3.4.2
在matplotlib v3.4.2版之前使用

  • 根据当前代码,
    w=0.8/3
    的注释将解决此问题
  • 但是,使用
#你的颜色
颜色=['#5cb85c'、'#5bc0de'、'#d9534f']
#带注释的绘图可能更容易
p1=df.plot.bar(color=colors,figsize=(20,8),ylabel='Percentage',title=“受访者对不同数据科学领域感兴趣的百分比”)
p1.setxticklabels(p1.getxticklabels(),旋转=0)
对于p1.1中的p:
p1.注释(f'{p.get_height():0.2f}',(p.get_x()+p.get_width()/2.,p.get_height()),ha='center',va='center',xytext=(0,10),textcoords='offset points')

Woo,非常感谢。你的代码比我的旧代码优雅多了。谢谢