1

I would like to plot histogram with pandas dataframe. I have four columns in my dataframe, but I would like to pick two of them and plot it. I plug in xaxis and yaxis values and draw three sub historgrams.

Here's how my code looks like:

fig = plt.figure(figsize=(9,7), dpi=100)

h = plt.hist(x=df_mean_h ['id'], y=df_mean_h ['mean'], 
color='red', label='h')

c = plt.hist(x=df_mean_c ['id'], y=df_mean_c ['mean'], 
color='blue', label='c')

o = plt.hist( x=df_mean_o['id'], y=df_mean_o ['mean'], 
color='green', label='o')

plt.show()

When I try to see the histogram, it displays nothing on the screen. How should I fix my code?

3
  • I can just guess: plt.show() ? Alternatively you could use DataFrame.plot.hist(by=None, bins=10, **kwds) see pandas.pydata.org/pandas-docs/stable/generated/… Commented Aug 15, 2017 at 16:49
  • I added plt.show() but it throws an error saying ValueError: setting an array element with a sequence. Commented Aug 15, 2017 at 17:40
  • your error probably stems from the fact that you do not pass an array to the plot but a pandas object. Check out the difference between df_mean_o['id'] and df_mean_o['id'].values Commented Aug 15, 2017 at 20:28

1 Answer 1

1
  1. You need to show the plot with plt.show()

  2. plt.hist() works differently than scatter or a series. You can't send x= and y=

https://matplotlib.org/1.2.1/examples/pylab_examples/histogram_demo.html

To make your example work, just send plt.hist a single column to create the chart:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
 'two' : pd.Series([1., 2., 3.], index=['a', 'b', 'c'])}
DF = pd.DataFrame(d)
fig = plt.figure(figsize=(9,7), dpi=100)

plt.hist(DF['two'])

plt.show()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Is there any way that I can show three histograms all together in one plot? I have to combine three histograms.
you can make axis with fig, ax = plt.subplots(ncols=1) and then do ax.plot(...) or dataframe.plot.hist(..., ax=ax)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.