[英]R, ggplot 2 bar graph x axis tick mark names disappear
I'm new to R and programming so please forgive me if this is a simple fix. 我是R和程序设计的新手,如果这是简单的解决方法,请原谅我。 I'm trying to label my x-axis tick marks on a bar graph in ggplot2 but when I run the code the entire x-axis tick-mark names disappear and I'm only left with the axis title. 我试图在ggplot2的条形图中标记我的x轴刻度线,但是当我运行代码时,整个x轴刻度线名称消失了,只剩下轴标题了。
Here is a picture of the problem 这是问题的图片
Here is my code: 这是我的代码:
#creating a bar graph of the "income" varibale
bar_graph_income <- ggplot(PRCPS, aes(income)) + geom_bar() + labs(title
= "How much money are American families making?", subtitle = "Pew
Research April 17 Political Survey") + labs(x="Income Ranges", y="Survey
Responses") + theme_bw()
#creating breaks and naming ticks
bar_graph_income <- bar_graph_income + scale_x_discrete(breaks=c("1","2","3","4","5","6","7","8","9") , labels=c("1" = "Below $10,000", "2" = "$10,000-$19,999", "3" = "$20,000-$29,999", "4" = "$30,000-$39,999", "5" = "$40,000-$49,999", "6" = "$50,000-$74,999", "7" = "$75,000-$99,999", "8" = "$100,000-$149,999", "9" = "$150,000 or more"))
#changing the text of the title
bar_graph_income <- bar_graph_income + theme(plot.title=element_text(family="Times", face="bold", size=14))
#changing the rest of the text
bar_graph_income<- bar_graph_income + theme(axis.text = element_text(family="Times", size=12, colour="black"))
#calling bar_graph_income
bar_graph_income
Thank you very much for your help 非常感谢您的帮助
It is a little difficult to diagnose without sample data, but I believe the issue is caused because you are calling scale_x_discrete
on continuous data ( income
). 没有样本数据很难诊断,但是我相信是由于您在连续数据( income
)上调用scale_x_discrete
引起的。
You can get around this by setting limits
first: 您可以通过先设置limits
来解决此问题:
bar_graph_income <- bar_graph_income +
scale_x_discrete(limits=1:9, labels = c("Below $10,000", "$10,000-$19,999", "$20,000-$29,999",
"$30,000-$39,999", "$40,000-$49,999", "$50,000-$74,999",
"$75,000-$99,999", "$100,000-$149,999", "$150,000 or more"))
You can also do this in one call with ggplot2
: 您也可以使用ggplot2
在一个调用中执行此ggplot2
:
bar_graph_income <- ggplot(PRCPS, aes(income)) +
geom_bar() +
labs(title = "How much money are American families making?",
subtitle = "Pew Research April 17 Political Survey",
x = "Income Ranges", y = "Survey Responses") +
theme_bw() +
scale_x_discrete(limits=1:9, labels = c("Below $10,000", "$10,000-$19,999", "$20,000-$29,999",
"$30,000-$39,999", "$40,000-$49,999", "$50,000-$74,999",
"$75,000-$99,999", "$100,000-$149,999", "$150,000 or more")) +
theme(plot.title=element_text(family="Times", face="bold", size=14),
axis.text = element_text(family="Times", size=12, colour="black"))
Alternatively, you can mutate your income
field as a factor ( as.factor
) and set the levels appropriately before calling ggplot
. 另外,您可以在调用ggplot
之前将income
字段作为一个因子( as.factor
)进行突变,并适当地设置水平。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.