您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python怎么实现折线图、柱状图、饼图
数据可视化是数据分析中不可或缺的一环,Python凭借其丰富的库生态系统成为实现可视化的首选工具。本文将详细介绍如何使用Matplotlib和Seaborn库绘制折线图、柱状图和饼图,并通过实际代码示例展示完整实现过程。
## 一、环境准备与基础库介绍
### 1.1 安装必要库
在开始之前,请确保已安装以下Python库:
```python
pip install matplotlib seaborn numpy pandas
折线图适合展示数据随时间变化的趋势。
import matplotlib.pyplot as plt
import numpy as np
# 生成示例数据
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 创建画布和坐标系
plt.figure(figsize=(8, 4))
# 绘制折线图
plt.plot(x, y,
color='royalblue',
linestyle='-',
linewidth=2,
marker='o',
markersize=4,
label='sin(x)')
# 添加标题和标签
plt.title('Basic Line Chart', fontsize=14)
plt.xlabel('X Axis', fontsize=12)
plt.ylabel('Y Axis', fontsize=12)
# 添加图例和网格
plt.legend()
plt.grid(alpha=0.4)
# 显示图表
plt.show()
比较多个数据序列的趋势变化:
# 生成多组数据
x = np.arange(1, 11)
y1 = np.random.randint(10, 30, 10)
y2 = np.random.randint(20, 40, 10)
y3 = np.random.randint(5, 25, 10)
plt.figure(figsize=(9, 5))
# 绘制多条折线
plt.plot(x, y1, label='Product A', marker='s')
plt.plot(x, y2, label='Product B', marker='^')
plt.plot(x, y3, label='Product C', marker='D')
# 高级设置
plt.xticks(x, [f'Week {i}' for i in x]) # 自定义x轴刻度
plt.ylim(0, 50) # 设置y轴范围
# 添加数据标签
for a, b in zip(x, y1):
plt.text(a, b+1, str(b), ha='center')
plt.title('Sales Trend Comparison')
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
import seaborn as sns
import pandas as pd
# 创建DataFrame数据
df = pd.DataFrame({
'Month': ['Jan', 'Feb', 'Mar', 'Apr'],
'Revenue': [45, 37, 52, 48],
'Cost': [30, 25, 36, 32]
})
# 设置Seaborn样式
sns.set_style("whitegrid")
# 绘制折线图
sns.lineplot(data=df, x='Month', y='Revenue',
marker='o', label='Revenue')
sns.lineplot(data=df, x='Month', y='Cost',
marker='s', label='Cost')
plt.title('Business Performance')
plt.ylabel('Amount (million)')
plt.show()
适合比较不同类别的数值大小。
categories = ['A', 'B', 'C', 'D']
values = [15, 24, 18, 27]
plt.figure(figsize=(7, 5))
# 绘制柱状图
bars = plt.bar(categories, values,
color=['#3498db', '#2ecc71', '#f1c40f', '#e74c3c'],
width=0.6)
# 添加数据标签
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('Basic Bar Chart')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()
# 准备数据
labels = ['Q1', 'Q2', 'Q3', 'Q4']
men = [20, 35, 30, 35]
women = [25, 32, 34, 20]
x = np.arange(len(labels))
width = 0.35
fig, ax = plt.subplots(figsize=(9, 5))
# 绘制分组柱状图
rects1 = ax.bar(x - width/2, men, width, label='Men')
rects2 = ax.bar(x + width/2, women, width, label='Women')
# 自定义设置
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.set_ylabel('Scores')
ax.set_title('Scores by group and quarter')
ax.legend()
# 自动调整标签位置
fig.tight_layout()
plt.show()
countries = ['USA', 'China', 'Japan', 'Germany', 'UK']
gdp = [21.4, 14.3, 5.1, 3.9, 2.8]
plt.figure(figsize=(8, 4))
bars = plt.barh(countries, gdp, color='teal')
# 添加数据标签
for bar in bars:
width = bar.get_width()
plt.text(width, bar.get_y() + bar.get_height()/2,
f'${width}tr',
va='center')
plt.title('GDP Comparison (2020)')
plt.xlabel('Trillion USD')
plt.grid(axis='x', alpha=0.3)
plt.show()
适合展示比例分布关系。
sizes = [15, 30, 25, 10, 20]
labels = ['A', 'B', 'C', 'D', 'E']
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99', '#c2c2f0']
plt.figure(figsize=(6, 6))
# 绘制饼图
patches, texts, autotexts = plt.pie(
sizes,
labels=labels,
colors=colors,
autopct='%1.1f%%',
startangle=90,
explode=(0.05, 0, 0, 0, 0) # 突出第一块
)
# 设置文本样式
for text in texts:
text.set_size(12)
for autotext in autotexts:
autotext.set_size(10)
autotext.set_color('white')
plt.title('Basic Pie Chart', fontsize=14)
plt.show()
# 数据准备
data = [35, 25, 20, 15, 5]
labels = ['Group A', 'Group B', 'Group C', 'Group D', 'Group E']
# 创建子图
fig, ax = plt.subplots(figsize=(6, 6))
# 绘制环形图
wedges, _ = ax.pie(data, radius=1,
colors=sns.color_palette("Set2"),
wedgeprops=dict(width=0.3, edgecolor='w'))
# 添加图例
ax.legend(wedges, labels,
title="Categories",
loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1))
plt.title('Donut Chart')
plt.show()
# 创建Series数据
s = pd.Series([20, 30, 25, 25],
index=['A', 'B', 'C', 'D'])
# 直接调用plot方法
s.plot.pie(figsize=(6, 6),
autopct='%.1f%%',
explode=(0.1, 0, 0, 0),
shadow=True,
startangle=90)
plt.ylabel('') # 移除默认的ylabel
plt.title('Pie Chart from Pandas')
plt.show()
plt.savefig('chart.png', dpi=300, bbox_inches='tight')
plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows系统
plt.rcParams['axes.unicode_minus'] = False
plt.style.use('ggplot') # 可选: 'seaborn', 'fivethirtyeight'等
本文详细介绍了Python中使用Matplotlib和Seaborn绘制三种基础图表的方法:
折线图:最适合展示数据随时间变化的趋势
plt.plot()
或sns.lineplot()
marker
, linestyle
, linewidth
柱状图:最擅长比较不同类别的数值差异
plt.bar()
或plt.barh()
width
, color
, edgecolor
饼图:最有效展示整体中各部分的比例关系
plt.pie()
autopct
, explode
, startangle
实际应用中应根据数据特点和展示目的选择合适的图表类型。对于更复杂的可视化需求,可以结合Pandas的数据处理能力和Seaborn的高级图表功能来实现。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。