You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib绘图绿色部分缺失求助(Python 2.7.4环境)

解决Matplotlib双轴图表中绿色Speed线条不显示的问题

嘿,我帮你找到了问题所在!你的绿色Speed线条没显示出来,主要是两个小细节没处理好,咱们马上fix它:

问题根源

  1. 图表尺寸设置时机不对:你把plt.rcParams['figure.figsize'] = 12,5放在了plt.show()之后,这时候图表已经生成了,尺寸设置根本没生效。而你的时间序列数据超级多——2015年全年15分钟间隔,总共35040个数据点!默认的小图表会让这些点挤成一团,绿色线条直接“隐身”了。
  2. 时间轴标签拥挤:就算线条显示了,默认的x轴日期也会挤成一团,可读性极差,咱们顺便一起解决。

修改后的完整代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 先设置图表尺寸,一定要在创建图表之前!
plt.rcParams['figure.figsize'] = (12, 5)
plt.style.use('ggplot')
%matplotlib inline

# 生成时间序列数据(把变量名range改成date_range,避免覆盖Python内置函数)
date_range = pd.date_range('2015-01-01', '2015-12-31', freq='15min')
df = pd.DataFrame(index=date_range)

# 填充数据
df['speed'] = np.random.randint(low=0, high=60, size=len(df.index))
df['distance'] = df['speed'] * 0.25
df['cumulative_distance'] = df.distance.cumsum()

# 创建双轴图表
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

# 绘制线条,可选加linewidth让密集线条更明显
ax1.plot(df.index, df['speed'], 'g-', linewidth=0.5)
ax2.plot(df.index, df['distance'], 'b-', linewidth=0.5)

# 设置轴标签和样式
ax1.set_xlabel('Date')
ax1.set_ylabel('Speed', color='g')
ax2.set_ylabel('Distance', color='b')

# 旋转x轴标签,避免拥挤
plt.xticks(rotation=45)

plt.show()

关键修改点说明

  • 把plt.rcParams['figure.figsize']移到代码最开头,确保图表创建时就使用宽幅尺寸,给密集的时间点足够的展示空间
  • 给线条增加了linewidth=0.5(可选),让大量数据点组成的线条更清晰
  • 添加plt.xticks(rotation=45)旋转x轴日期标签,解决时间轴拥挤的问题
  • 把变量名range改成date_range,避免覆盖Python内置函数,养成良好编码习惯

这样修改后,你就能看到绿色的Speed线条正常显示在图表上啦!

内容的提问来源于stack exchange,提问作者Venugopal Bukkala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:25:11