【问题标题】:How to plot histogram with x and y axis from dataframe in python如何从python中的数据框中绘制带有x和y轴的直方图
【发布时间】:2017-08-15 15:57:48
【问题描述】:

我想用 pandas 数据框绘制直方图。我的数据框中有四列,但我想选择其中两列并绘制它。我插入 xaxis 和 yaxis 值并绘制三个子直方图。

我的代码如下所示:

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()

当我尝试查看直方图时,屏幕上什么也没有显示。我应该如何修复我的代码?

【问题讨论】:

  • 我只能猜到:plt.show() ?或者,您可以使用DataFrame.plot.hist(by=None, bins=10, **kwds) 请参阅pandas.pydata.org/pandas-docs/stable/generated/…
  • 我添加了plt.show(),但它抛出了一个错误说ValueError: setting an array element with a sequence.
  • 您的错误可能源于您没有将数组传递给绘图而是一个熊猫对象。查看df_mean_o['id']df_mean_o['id'].values之间的区别

标签: python pandas histogram


【解决方案1】:
  1. 您需要使用 plt.show() 显示绘图

  2. plt.hist() 的工作方式与分散或系列不同。你不能发送 x= 和 y=

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

要使您的示例正常工作,只需发送 plt.hist 单列来创建图表:

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()

【讨论】:

  • 谢谢!有什么方法可以在一个图中同时显示三个直方图?我必须合并三个直方图。
  • 你可以用fig, ax = plt.subplots(ncols=1)做轴,然后做ax.plot(...)dataframe.plot.hist(..., ax=ax)
猜你喜欢
  • 2015-10-16
  • 2018-01-26
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多