I'm new to R and programming so please forgive me if this is a simple fix. 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.
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
).
You can get around this by setting limits
first:
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
:
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.