在熊猫直方图中用不同的颜色绘制不同的值
数据挖掘
Python
熊猫
可视化
分配
直方图
2021-10-06 19:15:54
2个回答
没有任何内置函数可以直接在 pandas 中执行此操作,但是通过获取 的数组集合AxesSubplot
,对其进行迭代以检索 matplotlib 补丁,您可以获得所需的结果。
以下是一些可以使用的虚拟数据:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(low=0, high=3, size=(1000,16)))
现在,这里的魔法:
import matplotlib.pyplot as plt
# Plot and retrieve the axes
axes = df.hist(figsize=(12,6), sharex=True, sharey=True)
# Define a different color for the first three bars
colors = ["#e74c3c", "#2ecc71", "#3498db"]
for i, ax in enumerate(axes.reshape(-1)):
# Define a counter to ensure that if we have more than three bars with a value,
# we don't try to access out-of-range element in colors
k = 0
# Optional: remove grid, and top and right spines
ax.grid(False)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
for rect in ax.patches:
# If there's a value in the rect and we have defined a color
if rect.get_height() > 0 and k < len(colors):
# Set the color
rect.set_color(colors[k])
# Increment the counter
k += 1
plt.show()
其它你可能感兴趣的问题