欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 文化 > Pandas 9-绘制柱状图

Pandas 9-绘制柱状图

2024/10/24 3:21:25 来源:https://blog.csdn.net/qq_52964132/article/details/141786679  浏览:    关键词:Pandas 9-绘制柱状图

1. 准备数据

首先,需要准备一个DataFrame。

import pandas as pd  # 创建一个DataFrame  
data = {  'Name': ['Alice', 'Bob', 'Charlie', 'David'],    'Age': [24, 27, 22, 32],    'City': ['New York', 'Los Angeles', 'Chicago', 'Houston'],    'Score': [85, 92, 78, 88]}  df = pd.DataFrame(data)  
print(df)  

输出:

      Name  Age         City  Score0    Alice   24     New York     85  
1      Bob   27  Los Angeles     92  
2  Charlie   22      Chicago     78  
3    David   32      Houston     88  

2. 绘制简单柱状图

可以使用plot方法来绘制柱状图。默认情况下,plot方法会绘制折线图,需要指定kind='bar'来绘制柱状图。

import matplotlib.pyplot as plt  # 绘制Age列的柱状图  
df['Age'].plot(kind='bar')  
plt.title('Age Distribution')  
plt.xlabel('Index')  
plt.ylabel('Age')  
plt.show()  

image.png

3. 绘制多列柱状图

如果想绘制多列的柱状图,可以将DataFrame传递给plot方法,并指定kind='bar'

# 绘制Age和Score列的柱状图  
df[['Age', 'Score']].plot(kind='bar')  
plt.title('Age and Score Distribution')  
plt.xlabel('Index')  
plt.ylabel('Value')  
plt.legend()  
plt.show()  

image.png

4. 绘制分组柱状图

可以使用plot方法的subplots参数来绘制分组柱状图。

# 绘制分组柱状图  
df[['Age', 'Score']].plot(kind='bar', subplots=True)  
plt.title('Age and Score Distribution')  
plt.xlabel('Index')  
plt.ylabel('Value')  
plt.legend()  
plt.show()  

image.png

5. 绘制堆积柱状图

可以使用stacked=True参数来绘制堆积柱状图。

# 绘制堆积柱状图  
df[['Age', 'Score']].plot(kind='bar', stacked=True)  
plt.title('Age and Score Stacked Distribution')  
plt.xlabel('Index')  
plt.ylabel('Value')  
plt.legend()  
plt.show()  

image.png

6. 自定义柱状图

可以通过Matplotlib的API来自定义柱状图的样式和标签。

# 自定义柱状图  
ax = df['Age'].plot(kind='bar', color='skyblue')  
ax.set_title('Customized Age Distribution')  
ax.set_xlabel('Index')  
ax.set_ylabel('Age')  
ax.set_xticklabels(df['Name'], rotation=45)  
plt.show()  

image.png

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com