来源
https://yalvtour.com
https://sdcbpay.com
https://qihuiwang02.com
pip install matplotlibimport matplotlib.pyplot as plt
import numpy as np# 创建数据
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 创建图表
plt.figure(figsize=(10, 6))
# 绘制线图
plt.plot(x, y, label='正弦曲线', color='blue', linewidth=2)
# 添加标题和标签
plt.title('正弦函数曲线', fontsize=14)
plt.xlabel('X轴', fontsize=12)
plt.ylabel('Y轴', fontsize=12)
# 添加图例
plt.legend()
# 显示图表
plt.show()正弦函数曲线图显示区域
基础线图示例效果
# 创建多个数据集
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x) * np.cos(x)
plt.figure(figsize=(10, 6))
# 绘制多条线
plt.plot(x, y1, label='正弦函数', color='royalblue', linestyle='-', linewidth=2.5)
plt.plot(x, y2, label='余弦函数', color='crimson', linestyle='--', linewidth=2.5)
plt.plot(x, y3, label='混合函数', color='forestgreen', linestyle='-.', linewidth=2.5)
plt.title('三角函数对比', fontsize=14)
plt.xlabel('X值', fontsize=12)
plt.ylabel('Y值', fontsize=12)
plt.legend()
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()# 带标记点的线图
x = np.linspace(0, 10, 15) # 较少的数据点
y = x**2 + np.random.randn(15)*2 # 带噪声的数据
plt.figure(figsize=(10, 6))
# 绘制带标记的线
plt.plot(x, y,
marker='o', # 圆形标记
markersize=8, # 标记大小
markerfacecolor='gold',
markeredgecolor='darkorange',
markeredgewidth=1.5,
linestyle=':',
linewidth=2,
color='darkorange',
label='二次函数')
plt.title('带标记点的线图', fontsize=14)
plt.xlabel('X轴', fontsize=12)
plt.ylabel('Y轴', fontsize=12)
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()import pandas as pd
import matplotlib.dates as mdates
# 创建模拟股票数据
date_rng = pd.date_range(start='2023-01-01', end='2023-06-30', freq='D')
price = np.cumsum(np.random.randn(len(date_rng)) * 0.5 + 100
volume = np.random.randint(10000, 50000, size=len(date_rng))
# 创建图表
fig, ax1 = plt.subplots(figsize=(12, 7))
# 绘制价格线图
ax1.plot(date_rng, price, color='royalblue', linewidth=2.5, label='股价')
ax1.set_title('2023年上半年股票价格趋势', fontsize=16)
ax1.set_ylabel('价格 (美元)', fontsize=12)
ax1.grid(True, linestyle='--', alpha=0.3)
# 设置x轴为日期格式
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
ax1.xaxis.set_major_locator(mdates.MonthLocator())
# 创建第二个y轴用于成交量
ax2 = ax1.twinx()
ax2.bar(date_rng, volume, color='lightgreen', alpha=0.5, width=0.8, label='成交量')
ax2.set_ylabel('成交量', fontsize=12)
# 添加图例
lines, labels = ax1.get_legend_handles_labels()
bars, bar_labels = ax2.get_legend_handles_labels()
ax2.legend(lines + bars, labels + bar_labels, loc='upper left')
# 优化布局
plt.tight_layout()
plt.show()股票价格趋势图显示区域
股票价格趋势分析图示例
通过本教程,您已经掌握了使用Python的Matplotlib库创建专业线图的技能:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。