您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 怎么用Python绘制柱形图
柱形图(Bar Chart)是数据可视化中最基础的图表类型之一,通过不同高度的矩形条展示各类别数据的对比关系。Python凭借丰富的可视化库(如Matplotlib、Seaborn、Plotly等)可以快速生成专业级柱形图。本文将详细讲解5种主流绘制方法,并提供完整代码示例。
## 一、基础工具准备
### 1.1 安装必备库
```bash
pip install matplotlib pandas seaborn plotly
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
categories = ['A', 'B', 'C', 'D']
values = [15, 24, 18, 27]
plt.figure(figsize=(8, 6))
bars = plt.bar(categories, values,
color='skyblue',
edgecolor='navy',
linewidth=2)
# 添加数据标签
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f'{height}',
ha='center', va='bottom')
plt.title('基础柱形图示例', fontsize=14)
plt.xlabel('类别', fontsize=12)
plt.ylabel('数值', fontsize=12)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
labels = ['Q1', 'Q2', 'Q3', 'Q4']
men_means = [20, 34, 30, 35]
women_means = [25, 32, 34, 20]
x = np.arange(len(labels))
width = 0.35 # 柱宽
fig, ax = plt.subplots(figsize=(10,6))
rects1 = ax.bar(x - width/2, men_means, width,
label='男性', color='royalblue')
rects2 = ax.bar(x + width/2, women_means, width,
label='女性', color='lightcoral')
ax.set_ylabel('销售额(万元)')
ax.set_title('季度销售数据对比')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
# 自动调整标签位置
fig.tight_layout()
plt.show()
df = pd.DataFrame({
'城市': ['北京', '上海', '广州', '深圳'],
'GDP': [40300, 43200, 28200, 30600],
'人口': [2171, 2487, 1868, 1756]
})
ax = df.plot.bar(x='城市', y=['GDP', '人口'],
figsize=(10,6),
color=['#1f77b4', '#ff7f0e'],
rot=0)
ax.set_title('城市经济数据对比', pad=20)
ax.set_ylabel('数值')
plt.grid(axis='y', alpha=0.3)
plt.show()
product_data = pd.DataFrame({
'Quarter': ['Q1', 'Q2', 'Q3', 'Q4'],
'Product_A': [230, 145, 180, 210],
'Product_B': [120, 195, 210, 180],
'Product_C': [90, 110, 130, 150]
})
ax = product_data.plot.bar(x='Quarter',
stacked=True,
figsize=(10,6),
colormap='Paired')
ax.set_ylabel('销售额(万)')
ax.set_title('季度产品销售额堆叠图')
plt.legend(bbox_to_anchor=(1.05, 1))
plt.tight_layout()
plt.show()
import seaborn as sns
tips = sns.load_dataset("tips")
plt.figure(figsize=(10,6))
ax = sns.barplot(x="day", y="total_bill",
data=tips,
ci=95, # 95%置信区间
palette="Blues_d",
capsize=0.1)
ax.set_title('每日账单金额分布(含置信区间)')
plt.show()
plt.figure(figsize=(12,7))
sns.set(style="whitegrid")
ax = sns.barplot(x="day", y="total_bill",
hue="sex",
data=tips,
palette=["#3498db", "#e74c3c"],
saturation=0.8)
ax.set_title('不同性别每日消费对比')
ax.legend(title='性别')
plt.show()
import plotly.express as px
data = px.data.gapminder().query("country == ['China', 'India', 'Japan']")
fig = px.bar(data, x='year', y='pop',
color='country',
title='亚洲人口大国人口变化',
labels={'pop':'人口数量'},
height=500)
fig.update_layout(hovermode="x unified")
fig.show()
df = px.data.gapminder()
fig = px.bar(df, x="continent", y="gdpPercap",
animation_frame="year",
color="continent",
hover_name="country",
range_y=[0,50000])
fig.update_layout(title='各大洲人均GDP年度变化')
fig.show()
from matplotlib.cm import ScalarMappable
data = [12, 25, 18, 30, 22]
colors = plt.cm.viridis(np.linspace(0, 1, len(data)))
fig, ax = plt.subplots(figsize=(10,6))
bars = ax.bar(range(len(data)), data, color=colors)
# 添加渐变色条
sm = ScalarMappable(cmap='viridis',
norm=plt.Normalize(min(data), max(data)))
plt.colorbar(sm, ax=ax)
plt.title('渐变色柱形图示例')
plt.show()
from matplotlib.patches import Rectangle
fig, ax = plt.subplots(figsize=(10,6))
for i, val in enumerate([20, 35, 30, 25]):
rect = Rectangle((i-0.4, 0), 0.8, val,
color='#3498db',
linewidth=2,
edgecolor='#2980b9',
joinstyle='round', # 关键参数
capstyle='round')
ax.add_patch(rect)
ax.text(i, val+1, str(val), ha='center')
ax.set_xlim(-0.5, 4)
ax.set_ylim(0, 40)
ax.set_xticks([0,1,2,3])
ax.set_xticklabels(['A','B','C','D'])
plt.title('圆角柱形图')
plt.show()
plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows
plt.rcParams['axes.unicode_minus'] = False
plt.xticks(rotation=45, ha='right') # 旋转45度
plt.bar(x, height, width=0.6) # 默认0.8
months = ['Jan', 'Feb', 'Mar', 'Apr']
sales = [120, 145, 130, 160]
target = [100, 120, 150, 140]
fig, ax = plt.subplots(figsize=(10,6))
ax.bar(months, sales, label='实际销售')
ax.plot(months, target, 'ro--', label='销售目标')
ax.set_title('月度销售达成情况')
ax.legend()
plt.show()
questions = ['问题1', '问题2', '问题3']
agree = [75, 60, 45]
disagree = [25, 40, 55]
x = np.arange(len(questions))
plt.figure(figsize=(10,6))
plt.barh(x + 0.2, agree, 0.4, label='同意')
plt.barh(x - 0.2, disagree, 0.4, label='不同意')
plt.yticks(x, questions)
plt.legend()
plt.title('问卷调查结果')
plt.show()
plt.hist()
或采样显示plt.savefig('output.pdf', format='pdf', dpi=300)
plt.clf()
清除当前图形而非创建新figure# 准备数据
np.random.seed(42)
categories = ['电子产品', '服装', '食品', '家居']
q1_sales = np.random.randint(50, 200, size=4)
q2_sales = np.random.randint(60, 250, size=4)
# 创建画布
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16,6))
# 子图1:季度对比
width = 0.35
x = np.arange(len(categories))
ax1.bar(x - width/2, q1_sales, width, label='第一季度')
ax1.bar(x + width/2, q2_sales, width, label='第二季度')
ax1.set_title('分季度销售对比')
ax1.set_xticks(x)
ax1.set_xticklabels(categories)
ax1.legend()
# 子图2:增长率
growth_rate = (q2_sales - q1_sales)/q1_sales * 100
colors = ['green' if x >=0 else 'red' for x in growth_rate]
ax2.bar(categories, growth_rate, color=colors)
ax2.axhline(0, color='black', linewidth=0.8)
ax2.set_title('季度增长率(%)')
plt.tight_layout()
plt.show()
通过以上示例,我们可以看到Python绘制柱形图既简单又强大。不同库有各自的特点: - Matplotlib:最基础灵活,适合需要精细控制的场景 - Pandas:与DataFrame完美集成,快速可视化 - Seaborn:统计特性丰富,美观的默认样式 - Plotly:交互式可视化,适合网页展示
建议初学者从Matplotlib开始掌握基本原理,再根据实际需求选择更高级的库。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。