我想将 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/