用不同颜色绘制Pandas不同列的直方图

2024-10-01 00:29:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

enter image description here

我尝试使用df.hist()绘制列,因此它给出了以下图形:

enter image description here

正如您所看到的,图形有一些重叠(下部图形的标题覆盖上部图形的x轴)。另一个问题与它们的颜色有关。正如你们所看到的,所有的图都是蓝色的,我想要有不同颜色的图,并且是分开的。例如,题为maxspeed的图形为绿色,FID_Json为黄色,依此类推


Tags: 数据json图形标题示例df颜色绘制
1条回答
网友
1楼 · 发布于 2024-10-01 00:29:15

下面是一个具有一些自定义功能的示例:

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

Subplots

相关问题 更多 >