python - X 标签 matplotlib

标签 python matplotlib timeserieschart

我想将 x 轴更改为年。年份保存在可变年份中。

我想绘制如下所示的数据图: It should look like this image

但是,我无法创建带有年份的 x 轴。我的情节如下图所示: This is an example of produced image by my code

我的代码如下所示:

import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv("data1.csv")
demand = data["demand"]
years = data["year"]
plt.plot( demand, color='black')
plt.xlabel("Year")
plt.ylabel("Demand (GW)")
plt.show()

非常感谢您的建议。

最佳答案

示例中的 plot 方法不知道数据的缩放比例。因此,为了简单起见,它将需求的值视为彼此分开的一个单位。如果您希望 x 轴代表年份,则必须告诉 matplotlib 它应该将多少个 demand 值视为“一年”。如果你的数据是每月的需求,那么显然每年是12个值。我们开始吧:

# setup a figure
fig, (ax1, ax2) = plt.subplots(2)

# generate some random data
data = np.random.rand(100)

# plot undesired way
ax1.plot(data)

# change the tick positions and labels ...
ax2.plot(data)

# ... to one label every 12th value
xticks = np.arange(0,100,12)

# ... start counting in the year 2000
xlabels = range(2000, 2000+len(xticks))

ax2.set_xticks(xticks)
ax2.set_xticklabels(xlabels)

plt.show()

关于python - X 标签 matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35231292/

相关文章:

python - matplotlib 3D 散点图点的颜色非常浅

python - CSV 数据的时间序列(时间戳和事件)

python Pandas : transform start and end datetime range (stored as 2 columns) to individual rows (eqpt utilisation)

python - plotly :如何在将鼠标悬停在三个y布局和一个x轴共享图上时显示所有堆叠的y轴数据值?

python - 在 python 中聚合时间序列

python - 子集 Pandas 数据框

android - 找不到版本标签字符串。文件必须更新

python - %matplotlib 返回无效语法错误

javascript - 如何从 PyQT 调用 javascript 函数

python - 使用 python 将异国字符集转换为字符串