Matplotlib:如何在 y 轴上绘制分类数据?
Matplotlib: how to plot categorical data on the y-axis?
假设我有以下代码,它来自 :
gender = ['male','male','female','male','female']
import matplotlib.pyplot as plt
from collections import Counter
c = Counter(gender)
men = c['male']
women = c['female']
bar_heights = (men, women)
x = (1, 2)
fig, ax = plt.subplots()
width = 0.4
ax.bar(x, bar_heights, width)
ax.set_xlim((0, 3))
ax.set_ylim((0, max(men, women)*1.1))
ax.set_xticks([i+width/2 for i in x])
ax.set_xticklabels(['male', 'female'])
plt.show()
如何将类别 male
和 female
绘制在 y 轴上,而不是 x 轴?
也许您正在寻找 barh
:
gender = ['male','male','female','male','female']
import matplotlib.pyplot as plt
from collections import Counter
c = Counter(gender)
men = c['male']
women = c['female']
bar_heights = (men, women)
y = (1, 2)
fig, ax = plt.subplots()
width = 0.4
ax.barh(y, bar_heights, width)
ax.set_ylim((0, 3))
ax.set_xlim((0, max(men, women)*1.1))
ax.set_yticks([i+width/2 for i in y])
ax.set_yticklabels(['male', 'female'])
plt.show()
假设我有以下代码,它来自
gender = ['male','male','female','male','female']
import matplotlib.pyplot as plt
from collections import Counter
c = Counter(gender)
men = c['male']
women = c['female']
bar_heights = (men, women)
x = (1, 2)
fig, ax = plt.subplots()
width = 0.4
ax.bar(x, bar_heights, width)
ax.set_xlim((0, 3))
ax.set_ylim((0, max(men, women)*1.1))
ax.set_xticks([i+width/2 for i in x])
ax.set_xticklabels(['male', 'female'])
plt.show()
如何将类别 male
和 female
绘制在 y 轴上,而不是 x 轴?
也许您正在寻找 barh
:
gender = ['male','male','female','male','female']
import matplotlib.pyplot as plt
from collections import Counter
c = Counter(gender)
men = c['male']
women = c['female']
bar_heights = (men, women)
y = (1, 2)
fig, ax = plt.subplots()
width = 0.4
ax.barh(y, bar_heights, width)
ax.set_ylim((0, 3))
ax.set_xlim((0, max(men, women)*1.1))
ax.set_yticks([i+width/2 for i in y])
ax.set_yticklabels(['male', 'female'])
plt.show()