JurajRabcan
JurajRabcan

Reputation: 133

X labels matplotlib

I want to change x axis to years. The years are saves in the variable years.

I want to make plot of my data that looks like this: It should look like this image

However, I am not able to create x axes with a years. My plot looks like the following image: This is an example of produced image by my code

My code looks as follows:

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()

I am thankful for any advice.

Upvotes: 1

Views: 1537

Answers (1)

MaxPowers
MaxPowers

Reputation: 5486

The plot method in your example does not know the scaling of your data. So, for simplicity it treats the values of demand as being one unit apart from each other. If you want your x-axis to represent years, you have to tell matplotlib how many values of demand it should treat as "one year". If your data is a monthly demand, it is obviously 12 values per year. And here we go:

# 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()

Upvotes: 2

Related Questions