简体   繁体   English

使用 Matplotlib 更改 x-ticks(字符串)中的名称

[英]Change name in x-ticks (strings) with Matplotlib

I am just starting with Matplotlib, and I want to create a simple bar plot with summarized data (I am using Jupyter Notebooks).我刚从 Matplotlib 开始,我想用汇总数据创建一个简单的条形图 plot(我使用的是 Jupyter Notebooks)。 The data are as follows:数据如下:

From a Pandas data frame:从 Pandas 数据帧:

by_gender = df.groupby(["Gender"])["Value"].mean().reset_index()

Result upon which I want to create the bar plot:我要在其上创建条形 plot 的结果:

Gender  Value
0   F   22.936350
1   M   15.897205

The code goes as follows:代码如下:

import matplotlib.pyplot as plt

x = by_gender["Gender"]
y = by_gender["Value"]
plt.bar(x, y, label = "Proportion", color = "#468499")
plt.title("% respondents accepting violence against women, by gender")
plt.xlabel("Gender")
plt.ylabel("Proportion %")
plt.legend()
plt.show()

This gives me the plot, no problem.这给了我 plot,没问题。 But now I want to change the x-ticks from "F" and "M" to "Female" and "Male."但现在我想将 x-ticks 从“F”和“M”更改为“Female”和“Male”。

I have googled A LOT, and tried all the functions I have found, including:我用谷歌搜索了很多,并尝试了我找到的所有功能,包括:

plt.xticks()
plt.set_ticks()
plt.set_xticks()
plt.set_xticklabels()

...and it gives me the same error no matter what: ...无论如何它都会给我同样的错误:

 AttributeError: module 'matplotlib.pyplot' has no attribute 'set_xticks' 

(substitute "set_xticks" for anything I proposed above) (用“set_xticks”代替我上面提出的任何内容)

I tried changing the intervals of the y-axis ticks just for kicks, and it gave me the same error.我尝试更改 y 轴刻度的间隔只是为了踢,它给了我同样的错误。 Is there anything wrong with how I am creating the plot?我如何创建 plot 有什么问题吗? I also tried creating a subplot, creating the variable fig...and nothing helps.我还尝试创建一个子图,创建变量 fig ......但没有任何帮助。

Thank you for your help.谢谢您的帮助。

You should manipulate the axis instead, as in:您应该改为操纵轴,如下所示:

fig, ax = plt.subplots()
ax.bar(x, y, label = "Proportion", color = "#468499")
ax.set_title("% respondents accepting violence against women, by gender")
ax.set_xlabel("Gender")
ax.set_ylabel("Proportion %")
ax.legend()
ax.set_xticklabels(['Female', 'Male'])
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM