Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add x and y labels to a pandas plot

Suppose I have the following code that plots something very simple using pandas:

import pandas as pd
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                   index=['Index 1', 'Index 2'])
df2.plot(lw=2, colormap='jet', marker='.', markersize=10, 
         title='Video streaming dropout by category')

Output

How do I easily set x and y-labels while preserving my ability to use specific colormaps? I noticed that the plot() wrapper for pandas DataFrames doesn't take any parameters specific for that.

like image 347
Everaldo Aguiar Avatar asked Oct 13 '22 07:10

Everaldo Aguiar


People also ask

How do you add X and Y axis labels in python?

To set labels on the x-axis and y-axis, use the plt. xlabel() and plt. ylabel() methods.


2 Answers

The df.plot() function returns a matplotlib.axes.AxesSubplot object. You can set the labels on that object.

ax = df2.plot(lw=2, colormap='jet', marker='.', markersize=10, title='Video streaming dropout by category')
ax.set_xlabel("x label")
ax.set_ylabel("y label")

enter image description here

Or, more succinctly: ax.set(xlabel="x label", ylabel="y label").

Alternatively, the index x-axis label is automatically set to the Index name, if it has one. so df2.index.name = 'x label' would work too.

like image 426
TomAugspurger Avatar answered Oct 17 '22 05:10

TomAugspurger


You can use do it like this:

import matplotlib.pyplot as plt 
import pandas as pd

plt.figure()
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                   index=['Index 1', 'Index 2'])
df2.plot(lw=2, colormap='jet', marker='.', markersize=10,
         title='Video streaming dropout by category')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.show()

Obviously you have to replace the strings 'xlabel' and 'ylabel' with what you want them to be.

like image 61
jesukumar Avatar answered Oct 17 '22 04:10

jesukumar