8

this might be really a simple question for most of you guys using matplotlib. Please help me out. I want to plot two array like [1,2,3,4] and [4,5,6,7] versus time in a same plot. I am trying to use matplotlib.pyplot.plot_date but couldn't figure out how to do it. It seems to me that only one trend can be plotted with plot_date in one plot.

Thank you in advance

Joe Kington
  • 275,208
  • 71
  • 604
  • 463
Siv Niznam
  • 161
  • 1
  • 3
  • 4

1 Answers1

13

To use plot date with multiple trends, it's easiest to call it multiple times. For example:

import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Generate Data
time = mdates.drange(datetime.datetime(2010, 1, 1), 
                     datetime.datetime(2011, 1, 1),
                     datetime.timedelta(days=10))
y1 = np.cumsum(np.random.random(time.size) - 0.5)
y2 = np.cumsum(np.random.random(time.size) - 0.5)

# Plot things...
fig = plt.figure()

plt.plot_date(time, y1, 'b-')
plt.plot_date(time, y2, 'g-')

fig.autofmt_xdate()
plt.show()

enter image description here

Alternately you can use a single plot (rather than plot_date) call and then call plt.gca().xaxis_date(), if you'd prefer. plot_date just calls plot and then ax.xaxis_date().

Joe Kington
  • 275,208
  • 71
  • 604
  • 463
  • Thanks a lot, It worked. I have one more question though. What if I want to add multiple scale for each of the data in y-axis? I am not asking about adding one secondary axis but different scale for different trends which can be placed vertically. – Siv Niznam Sep 08 '11 at 17:25
  • Do you just mean subplots? http://matplotlib.sourceforge.net/examples/pylab_examples/ganged_plots.html – Joe Kington Sep 08 '11 at 17:46
  • Joe, thanks for reply. I don't mean subplots. I mean the same graph with multiple scale for each trend. – Siv Niznam Sep 08 '11 at 17:51
  • Well, keep in mind that this is essentially what subplots do. You just need to hide the boundaries between them. This is a horizontal example, instead of stacking along the y-axis: http://i.stack.imgur.com/Xllnj.png but the idea is the same. (That example plot is from this question http://stackoverflow.com/questions/6326360/python-matplotlib-probability-plot-for-several-data-set/6339311#6339311 ) If that's not what you had in mind, have a look at `twinx`, but I don't think twinx is what you're wanting from your description. – Joe Kington Sep 08 '11 at 19:39
  • Hi, How can I mark the lines, like Green = "aaaa", blue="bbbb" – SanalBathery May 23 '16 at 20:23