如何使用Matplotlib在直方图中按组填充颜色?

时间:2019-06-17 20:26:50

标签: python r matplotlib histogram data-visualization

我知道如何在R中执行此操作,并在下面提供了代码。我想知道如何做与Python Matplotlib中下面提到的类似的事情或使用任何其他库

library(ggplot2)
ggplot(dia[1:768,], aes(x = Glucose, fill = Outcome)) +
  geom_bar() +
  ggtitle("Glucose") +
  xlab("Glucose") +
  ylab("Total Count") +
  labs(fill = "Outcome")

2 个答案:

答案 0 :(得分:0)

请考虑以下示例,该示例使用seaborn

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# generate random data
data = {'Glucose': np.random.normal(5, 10, 100),
        'Outcome': np.random.randint(2, size=100)}
df = pd.DataFrame(data)

# plot
fig, ax = plt.subplots(figsize=(10, 10))
for group in df.Outcome.unique():
    sns.distplot(df.loc[df.Outcome == group, 'Glucose'],
                 kde=False, ax=ax, label=group)

ax.set_xlabel('Glucose')
ax.set_ylabel('Total Count')
ax.set_title('Glucose')
ax.legend()

答案 1 :(得分:0)

使用熊猫,您可以旋转数据框并直接绘制它。

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

# dataframe with two columns in "long form"
g = np.array([np.random.normal(5, 10, 500),
              np.random.rayleigh(10, size=500)]).flatten()
df = pd.DataFrame({'Glucose': g, 'Outcome': np.repeat([0,1],500)})

# pivot and plot
df.pivot(columns="Outcome", values="Glucose").plot.hist(bins=100)

plt.show()

enter image description here