【问题标题】:Plotting histograms with different color for different columns in Pandas [closed]为 Pandas 中的不同列绘制不同颜色的直方图 [关闭]
【发布时间】:2021-10-01 00:08:10
【问题描述】:

我有一个包含 5 列的数据框,我将把所有列绘制在一起,但使用不同的直方图,每个直方图的颜色不同。此图显示了我的数据示例。

我尝试使用 df.hist() 绘制列,所以它给了我以下图表:

如您所见,图表有一些重叠(下图的标题覆盖了上图的 x 轴)。另一个问题与它们的颜色有关。如您所见,所有图表都是蓝色的,我希望有不同颜色的图表并分开。例如,maxspeed 为绿色,FID_Json 为黄色,以此类推。

【问题讨论】:

  • 请将数据发布为代码而不是屏幕截图。另外,你刚才不是问过这个完全相同的问题,然后被关闭了吗?您对之前提出的问题没有任何改进。
  • 尝试使用matplotlibimport matplotlib.pyplot as plt,然后使用fig, (ax1, ax2, ax3, ax4) = plt.subplots(2,2),在每个轴上绘制直方图,您可以为每个轴设置颜色
  • df.plot(kind='hist', subplots=True, layout=(2, 2)) 并确保将matplotlibpandas 分别更新为3.4.21.3.0 的当前版本。

标签: python pandas matplotlib


【解决方案1】:

这是一个带有一些自定义的示例:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import itertools

# create test dataframe
df = pd.DataFrame({
    'FID_Json_M': [1903, 1904, 1905],
    'maxspeed': [50,50,50],
    'direction': ['South','South','South'],
    'roadtype': ['secondary','secondary','secondary']
})

# define colors for subplots
colors = ['red', 'green', 'blue', 'orange']

# create 2 x 2 subplots
fig, axes = plt.subplots(nrows = 2, ncols = 2)
# set padding between subplots
fig.tight_layout(pad=1.0)

# iterate over subplots in figure  and colunds in dataframe
for col, ax in zip(df.columns, list(itertools.chain(*axes))):
  # create histogram for each data series using specified color
  ax.hist(df[col], color = colors[list(df.columns).index(col)]) 

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 2022-11-13
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多