fig, ax = plt.subplots(figsize=(15, 12)) ax.barh([data["Gender"]=="Female"]data["Income"], width=0.7, label="Female") ax.barh([data["Gender"]=="Male"]data["Income"], width=0.7, label="Male") ax.set_xlabel("Income") ax.set_yticks(data.index) ax.set_yticklabels(data["MaritalStatus"]) ax.legend() plt.show()如何修改代码
时间: 2023-06-18 16:02:56 浏览: 51
您可以尝试以下代码:
```
fig, ax = plt.subplots(figsize=(15, 12))
female_income = data[data["Gender"]=="Female"]["Income"]
male_income = data[data["Gender"]=="Male"]["Income"]
ax.barh(data["MaritalStatus"], female_income, height=0.7, label="Female")
ax.barh(data["MaritalStatus"], male_income, height=0.7, left=female_income, label="Male")
ax.set_xlabel("Income")
ax.legend()
plt.show()
```
这里我们分别取出男性和女性的收入,分别作为两个 `barh` 的参数。同时在第二个 `barh` 中通过 `left` 参数将男性的柱形图放在女性柱形图的右侧。将 `set_yticks` 和 `set_yticklabels` 修改为 `data["MaritalStatus"]` 可以使 y 轴标签显示正确。
相关问题
fig, ax = plt.subplots(figsize=(15, 12)) ax.barh(data[["MaritalStatus", "Gender"]], data["Income"])
这段代码有一些问题,首先应该指定要绘制水平条形图的数据和条形的宽度。另外,不应该将两个变量合并在一起作为条形图的 x 轴,而应该使用分组条形图。以下是修改后的代码示例:
```
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv("data.csv")
# 分组条形图
fig, ax = plt.subplots(figsize=(15, 12))
width = 0.4
ax.barh(data.index - width/2, data["Income"][data["Gender"]=="Female"], height=width, label="Female")
ax.barh(data.index + width/2, data["Income"][data["Gender"]=="Male"], height=width, label="Male")
# 设置 x 轴标签和标题
ax.set_xlabel("Income")
ax.set_ylabel("MaritalStatus")
ax.set_title("Income by MaritalStatus and Gender")
# 设置 y 轴刻度标签
ax.set_yticks(data.index)
ax.set_yticklabels(data["MaritalStatus"])
# 添加图例
ax.legend()
plt.show()
```
这段代码会绘制一个按照婚姻状况和性别分组的条形图,横轴为收入,纵轴为婚姻状况,每个条形图代表一个性别。
fig, ax = plt.subplots(figsize=(15, 12))female_income = data[data["Gender"]=="Female"]["Income"]male_income = data[data["Gender"]=="Male"]["Income"]ax.barh(data["MaritalStatus"], female_income, height=0.7, label="Female")ax.barh(data["MaritalStatus"], male_income, height=0.7, left=female_income, label="Male")ax.set_xlabel("Income")ax.legend()plt.show()
这段代码使用了Matplotlib库绘制了一个水平条形图,用于比较不同婚姻状况下男性和女性的收入情况。
首先,通过plt.subplots()函数创建一个画布fig和一组子图ax,指定了画布的大小为(15,12)。
接着,从数据集中筛选出性别为女性和男性的数据,并分别赋值给female_income和male_income。
然后,使用ax.barh()函数分别绘制了女性和男性的水平条形图,其中参数data["MaritalStatus"]表示婚姻状况是x轴,female_income和male_income分别表示女性和男性的收入是y轴,height和left分别表示条形图的高度和水平位置。
最后,使用ax.set_xlabel()函数设置x轴的标签为“Income”,使用ax.legend()函数添加图例,并通过plt.show()函数显示图形。