繁体   English   中英

R,ggplot 2条形图x轴刻度标记名称消失

[英]R, ggplot 2 bar graph x axis tick mark names disappear

我是R和程序设计的新手,如果这是简单的解决方法,请原谅我。 我试图在ggplot2的条形图中标记我的x轴刻度线,但是当我运行代码时,整个x轴刻度线名称消失了,只剩下轴标题了。

这是问题的图片

这是我的代码:

#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

非常感谢您的帮助

没有样本数据很难诊断,但是我相信是由于您在连续数据( income )上调用scale_x_discrete引起的。

您可以通过先设置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"))

您也可以使用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"))

另外,您可以在调用ggplot之前将income字段作为一个因子( as.factor )进行突变,并适当地设置水平。

暂无
暂无

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

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