Use index in pandas to plot data

PythonPandas

Python Problem Overview


I have a pandas-Dataframe and use resample() to calculate means (e.g. daily or monthly means). Here is a small example.

import pandas as pd  
import numpy as np

dates = pd.date_range('1/1/2000', periods=100)
df = pd.DataFrame(np.random.randn(100, 1), index=dates, columns=['A'])

monthly_mean = df.resample('M').mean()

How do I plot the monthly_mean now?

How do I manage to use the index of my new created DataFrame monthly_mean as the x-axis?

Python Solutions


Solution 1 - Python

Try this,

monthly_mean.plot(y='A', use_index=True)

Solution 2 - Python

You can use reset_index to turn the index back into a column:

monthly_mean.reset_index().plot(x='index', y='A')

Look at monthly_mean.reset_index() by itself- the date is no longer in the index, but is a column in the dataframe, which is now just indexed by integers. If you look at the documentation for reset_index, you can get a bit more control over the process, including assigning sensible names to the index.

Solution 3 - Python

Also,

monthly_mean.plot(x=df.index, y='A')

Solution 4 - Python

monthly_mean.plot(y='A')

Uses index as x-axis by default.

Solution 5 - Python

  • When plotting line plots against the index, the simplest answer is to not assign any x or y.
  • This will plot lines for all numeric or datetime columns, without specifying y
monthly_mean.plot()

enter image description here

  • Only specify y= if there are multiple columns and you want certain columns plotted
  • Or select the columns before plotting (e.g. monthly_mean[[c1, c2, c5]].plot())
# sample data with multiple columns (5 x 5)
df = pd.DataFrame(np.random.random_sample((5, 5)))

# method 1: specify y
df.plot(y=[0, 2, 4])

# method 2: select columns first
df[[0, 2, 4]].plot()

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpaulchenView Question on Stackoverflow
Solution 1 - PythonPablo JadzinskyView Answer on Stackoverflow
Solution 2 - PythonMariusView Answer on Stackoverflow
Solution 3 - PythonPablo JadzinskyView Answer on Stackoverflow
Solution 4 - PythonNic ScozzaroView Answer on Stackoverflow
Solution 5 - PythonTrenton McKinneyView Answer on Stackoverflow