Ray
Ray

Reputation: 8573

Python Pandas plot multiindex specify x and y

Below is an example DataFrame.

           joaquin     manolo
xx 0  0.000000e+00  44.000000
   1  1.570796e+00  52.250000
   2  3.141593e+00  60.500000
   3  4.712389e+00  68.750000
   4  6.283185e+00  77.000000
yy 0  0.000000e+00  37.841896
   1  2.078796e+00  39.560399
   2  5.292179e-17  41.026434
   3 -8.983291e-02  42.304767
   4 -4.573916e-18  43.438054

As you can see, the row index has two levels, ['xx', 'yy'] and [0, 1, 2, 3, 4]. I want to call DataFrame.plot() in such a way that it will produce two subplots, one for joaquin and one for manolo, and where I can specify to use data.loc["xx", :] for the domain data and to use data.loc["yy", :] for the ordinate data. In addition, I want the option to supply the subplots on which the plots should be drawn, in a list (or array) of matplotlib.axes._subplots.AxesSubplot instances, such as those that can be returned by the DataFrame.hist() method. How can this be done?

Generating the data above

Just in case you're wondering, below is the code I used to generate the data. If there is an easier way to generate this data, I'd be very interested to know as a side-note.

joaquin_dict = {}
xx_joaquin = numpy.linspace(0, 2*numpy.pi, 5)
yy_joaquin = 10 * numpy.sin(xx_joaquin) * numpy.exp(-xx_joaquin)
for i in range(len(xx_joaquin)):
    joaquin_dict[("xx", i)] = xx_joaquin[i]
    joaquin_dict[("yy", i)] = yy_joaquin[i]

manolo_dict = {}
xx_manolo = numpy.linspace(44, 77, 5)
yy_manolo = 10 * numpy.log(xx_manolo)
for i in range(len(xx_manolo)):
    manolo_dict[("xx", i)] = xx_manolo[i]
    manolo_dict[("yy", i)] = yy_manolo[i]

data_dict = {"joaquin": joaquin_dict, "manolo": manolo_dict}
data = pandas.DataFrame.from_dict(data_dict)

Upvotes: 2

Views: 172

Answers (1)

HYRY
HYRY

Reputation: 97281

Just use a for loop:

fig, axes = pl.subplots(1, 2)
for ax, col in zip(axes, data.columns):
    data[col].unstack(0).plot(x="xx", y="yy", ax=ax, title=col)

output:

enter image description here

Upvotes: 3

Related Questions