Thomas Matthew
Thomas Matthew

Reputation: 2886

Syntax for matplotlib parameters on a pandas hist

According to the docs, the pandas hist method to create a dataframe can take a parameter ax to presumably pass some kind plotting parameters to the ax object. What I want to know is how I pass these parameters. Here is some code:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.normal(0,100,size=(100, 2)), columns=['col1', 'col2'])
pd.DataFrame.hist(df,column='col1', ax={ylim(-1000,1000), set_title('new title')})

The above code seeks to modify the y-axis limits and title using the ax parameter, but I'm not sure of the syntax to use.

Upvotes: 2

Views: 1996

Answers (1)

andrew_reece
andrew_reece

Reputation: 21264

It's the output of hist() that creates a Matplotlib Axes object. From the plot() docs:

Returns: axes : matplotlib.AxesSubplot or np.array of them

You can use that returned to make adjustments.

ax = df.col1.hist()
ax.set_title('new_title')
ax.set_ylim([-1000,1000])

The ax argument inside plot() (and variants like hist()) is used to plot on a predefined Axes element. For example, you can use ax from one plot to overlay another plot on the same surface:

ax = df.col1.hist()
df.col2.hist(ax=ax)

overlay plot

Note: I updated your syntax a bit. Call hist() as a method on the data frame itself.

UPDATE
Alternately, you can pass keywords directly, but in that case you (a) need to call plot.hist() instead of just hist(), and (b) the keywords are passed either as kwargs or directly in line. For example:

kwargs ={"color":"green"}
# either kwargs dict or named keyword arg work here
df.col1.plot.hist(ylim=(5,10), **kwargs) 

Upvotes: 2

Related Questions