2

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.

Thomas Matthew
  • 2,826
  • 4
  • 34
  • 58

1 Answers1

2

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) 
andrew_reece
  • 20,390
  • 3
  • 33
  • 58
  • The docs make it seem like you can do this directly from the call to `hist`, but I still can't figure out that approach. Thanks for you solution. – Thomas Matthew Dec 21 '17 at 06:42
  • 1
    You can do this too. I think you need `plot.hist()` though, then you can just pass keywords directly to Matplotlib's method, like `df.col1.plot.hist(ylim=(5,10))`. I'll add an example. – andrew_reece Dec 21 '17 at 06:47
  • 1
    The direct way is also referenced in [this answer](https://stackoverflow.com/a/38433359/2799941). – andrew_reece Dec 21 '17 at 06:50