1. 创建基础图表
1.1. 线形图
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.title('基础线形图')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.show()
1.2. 条形图
x = ['A', 'B', 'C', 'D']
y = [10, 20, 30, 40]
plt.bar(x, y)
plt.title('基础条形图')
plt.xlabel('类别')
plt.ylabel('数值')
plt.show()
1.3. 散点图
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.scatter(x, y)
plt.title('基础散点图')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.show()
2. 高级图表
2.1. 子图
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot([1, 2, 3], [1, 4, 9])
axs[0, 0].set_title('子图1')
axs[0, 1].bar([1, 2, 3], [1, 4, 9])
axs[0, 1].set_title('子图2')
axs[1, 0].scatter([1, 2, 3], [1, 4, 9])
axs[1, 0].set_title('子图3')
axs[1, 1].hist([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], bins=3)
axs[1, 1].set_title('子图4')
plt.tight_layout()
plt.show()
2.2. 箱线图
import numpy as np
data = np.random.normal(loc=0, scale=1, size=1000)
plt.boxplot(data)
plt.title('箱线图')
plt.xlabel('数据')
plt.show()
3. 动态图表
3.1. 动态更新数据
import matplotlib.animation as animation
fig, ax = plt.subplots()
x_data, y_data = [], []
def update(frame):
x_data.append(frame)
y_data.append(np.random.random())
ax.clear()
ax.plot(x_data, y_data)
ani = animation.FuncAnimation(fig, update, frames=100, interval=50)
plt.show()
3.2. 地图可视化
import geopandas as gpd
import matplotlib.pyplot as plt
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
fig, ax = plt.subplots(1, 1, figsize=(12, 8))
world.plot(ax=ax, color='white', edgecolor='black')
plt.show()
4. 高级定制
4.1. 自定义颜色
colors = ['#FF5733', '#FFC300', '#DAF7A6', '#C39BD3', '#E6E6FA']
plt.plot([1, 2, 3, 4, 5], [2, 3, 5, 7, 11], colors=colors)
plt.title('自定义颜色')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.show()
4.2. 自定义样式
styles = ['seaborn-darkgrid', 'seaborn-whitegrid', 'seaborn-dark-palette', 'seaborn-whitegrid']
plt.style.use(styles[0])
plt.plot([1, 2, 3, 4, 5], [2, 3, 5, 7, 11])
plt.title('自定义样式')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.show()
5. 交互式图表
5.1. Jupyter Notebook 中的交互式图表
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()
5.2. Plotly 交互式图表
import plotly.graph_objs as go
trace = go.Scatter(x=[1, 2, 3], y=[2, 3, 5])
data = [trace]
layout = go.Layout(title='交互式散点图', xaxis={'title': 'X轴'}, yaxis={'title': 'Y轴'})
fig = go.Figure(data=data, layout=layout)
fig.show()
通过以上20个实用示例,相信你已经对Matplotlib有了更深入的了解。Matplotlib是一个功能强大的工具,可以轻松实现各种数据可视化需求。在实际应用中,可以根据自己的需求选择合适的图表类型和样式,使数据可视化更加直观和有趣。