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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

司南锤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值