堆栈条形图

问题描述 投票:0回答:1

如何使我的图表 1 看起来像图表 2?我尝试了底部选项,但当我这样做时,它就到处都是。

图表1:

CHART 1

图2:

CHART 2

import matplotlib.pyplot as plt
import numpy as np


label = ['Math', 'Physics', 'English', 'Computer']
x = np.arange(len(label))
y1 = [100, 90, 80, 60]
y2 = [90, 80, 70, 100]
width = 0.35

fig, ax = plt.subplots()
rect1 = ax.bar(x-width/2, y1, width, label='Bill')
rect2 = ax.bar(x+width/2, y2, width, label='Mary')

ax.set_ylabel('Scores')
ax.set_title('Stacked graph for scores')
ax.legend()
ax.set_xticks(x, label)
# plt.xticks(x, label)
plt.legend(loc='upper right')

ax.bar_label(rect1, padding=3)
ax.bar_label(rect2, padding=3)
plt.show()

我正在尝试类似的事情,但我很困惑

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
students = ['John', 'Doe', 'Mary', 'Bill']
x = [1,2,3,4]
math = [80, 90, 50, 80]
english = [60, 80, 40, 50]

ax.bar(students, math)
ax.bar(students, english, bottom=math)
plt.show()
python matplotlib stacked-chart
1个回答
0
投票

我对列表定义做了一些更改和一些小的更改:

from typing import List

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

student_numbers: List[int] = [1, 2, 3, 4]
student_names: List[str] = ['John', 'Doe', 'Mary', 'Bill']
math_scores: List[int] = [80, 90, 50, 80]
english_scores: List[int] = [60, 80, 40, 50]

# Plot the math scores
ax.bar(student_numbers, math_scores, label='Math')

# Plot the English scores on top of the math scores, offsetting the y-axis
# position by the amount of the math scores.
ax.bar(student_numbers, english_scores, label='English', bottom=math_scores)

# Set the x-axis labels
ax.set_xticks(student_numbers)
ax.set_xticklabels(student_names)

# Set the y-axis labels
ax.set_ylabel('Score')

# Add a legend
ax.legend()

# Show the plot
plt.show()

输出:

© www.soinside.com 2019 - 2024. All rights reserved.