0

I am quite newbie into matplotlib and I am struggling to plot a line graph because of my x axis.

I have 3 lists:

x=[01-01-2018,02-01-2018,03-01-2018]
y1=[10,12,9]
y2=[7,9,1] 

I am looking forward to plot a 2 line graph setting in the x axis the dates:

I am looking forward to do this using subplots in order to customize the graphs as I like.

In order to do this what I tried was:

ax1=plt.subplot2grid((1,1),(0,0))
ax1.plot(x,y1,label='test1')
ax1.plot(x,y2,label='test2')

plt.show()  

However it outputs:

ValueError: could not convert string to float: '01-01-2018'

I would like an output the 2 line graph and in the x axis the dates. How can I display the desired output?

JamesHudson81
  • 2,215
  • 4
  • 23
  • 42

1 Answers1

0

You will need to modify the xticks directly. Here is an example that works:

y1 = [10, 12, 9]
y2 = [7, 9, 1]
x=['01-01-2018','02-01-2018','03-01-2018']
fig, ax = plt.subplots()
ax.plot(y1,label='test1')
ax.plot(y2, label='test2')
ax.set_xticks([0,1,2])
ax.set_xticklabels(x)
plt.show()

The line ax.set_xticks sets the specific ticks that will appear on the x axis for each point -- 0 is the tick for the first data point, 1 for the second etc.

ax.set_xticklabels takes a list of strings that must be equal in length to how many ticks you made. It then pairs each label to each tick.

You should also checkout the matplotlib documentation and examples.

rigby
  • 223
  • 2
  • 10