Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use dataframe column names as labels in pylab.plot

I would like to plot the data in a dataframe and have the column headers be the labels. I tried this:

dfm.columns = ['a','b']
plot(dfm.cumsum(), label= dfm.columns.values)
legend(loc='upper left')

But got this:

enter image description here

Instead of both lines being labeled ['a','b'], I'd like the blue line to be a and the green to be b using pylab

like image 854
TPM Avatar asked Oct 08 '15 16:10

TPM


People also ask

How do I plot data from pandas Dataframe to matplotlib?

Pandas has tight integration with matplotlib. You can plot data directly from your DataFrame using the plot () method: Scatter plot of two columns import matplotlib.pyplot as plt import pandas as pd # a scatter plot comparing num_children and num_pets df.plot(kind='scatter',x='num_children',y='num_pets',color='red') plt.show()

How to provide label as 1 2 3 or 4 in Python?

The objective is to provide label as 1, 2, 3, 4 etc. The above code creates a new column namely UNS_NEW. The data frame looks like the following: F ig 2. Python Data frame columns – Labels assigned new value Note that there is a new column with new labels (1, 2, 3, 4) assigned based on the logic within assignNewLabels function.

How to plot data directly from a Dataframe?

You can plot data directly from your DataFrame using the plot () method: Just reuse the Axes object. Instead of calling plt.show (), call plt.savefig ('outputfile.png'):

What is xlabel in Dataframe?

dataSeries or DataFrame The object for which the method is called. xlabel or position, default None Only used if data is a DataFrame.


1 Answers

I think it's the way you have your data set up in part of the code you're not showing.

Here's an example, I used df.plot() in this case.

import pandas as pd
import random
import matplotlib.pyplot as plt

x = [random.randint(10,20) for r in range(100)]
y = [random.randint(0,10) for r in range(100)]

df = pd.DataFrame([x,y]).T #T for transpose

df.columns=['a','b']

df.plot(kind='line')

plt.legend(loc='upper left')

plt.show()

enter image description here

Edit

pylab version

import pandas as pd
import random
import matplotlib.pylab as plt

x = [random.randint(10,20) for r in range(100)]
y = [random.randint(0,10) for r in range(100)]

df = pd.DataFrame([x,y]).T

plt.plot(df)

plt.legend(['a','b'],loc='upper left')

plt.show()
like image 161
Leb Avatar answered Sep 20 '22 17:09

Leb