简体   繁体   中英

Force x-axis labels for one facet in ggplot2

I am plotting data by country and each county has a different range of years with data so I'm using free_x in facet_wrap (x-axis = year) . One country (see Congo in attached image) ends up with years as decimals. Is there a way to force integers on the x-axis or manually edit the x-axis for a single facet?

data %>% 
  filter (Filter > 3 & Region == "Africa") %>% 
  ggplot(mapping = aes(x = year,
                       y = ln_P,
                       group = country)) +
  geom_smooth(method = "glm", formula =  y ~ poly(x,2), se=FALSE, 
              aes(weight=N), color = "grey")+
  geom_point(aes(shape = Source), size = 2) +
  theme_bw()+
  theme(text = element_text(family = "Times New Roman"), 
        legend.direction = "vertical",
        legend.position = c(0.8, 0.08), 
        legend.title = element_text(face="bold"), 
        strip.text = element_text(face="bold"),
        axis.text = element_text(color = "black")) +
  labs(y = "ln(P/100-P)", x = "Year") +
  scale_y_continuous(name = "ln(P/100-P)", breaks = c(-6, -4, -2, 0)) +
  facet_wrap(~country, scales = "free_x")

在此处输入图片说明

Without data, it's difficult to work out an answer: I would try this.

1) Install scales , a very handy package for scaling, if you haven't done this before.

2) Assume your above ggplot graph named p :

p + scale_x_continuous(
   labels = scales::number_format(accuracy = 1))  

If still not working, change your date (date class) into year:

data <- data %>% mutate(year = year(date)) 

Try 2) again, hope this helps.

Formatting year as a date solved the problem. Thank you!

data %>% 
  filter (Filter>3 & Region == "Africa") %>% 
  ggplot(mapping = aes(x = as.Date(as.character(year), "%Y"),
                   y = ln_P,
                   group = country)) +
  geom_smooth(method = "glm",formula =  y ~ poly(x,2), se=FALSE, aes(weight=N), color 
  = "grey")+
  geom_point(aes(shape = Source), size = 2) +
  theme_bw()+
  theme(text = element_text(family = "Times New Roman"), 
        legend.direction = "vertical",
        legend.position = c(0.8, 0.08), 
        legend.title = element_text(face="bold"), 
        strip.text = element_text(face="bold"),
        axis.text = element_text(color = "black")) +
  labs(y = "ln(P/100-P)", x = "Year") +
  scale_y_continuous(name = "ln(P/100-P)", breaks = c(-6, -4, -2, 0)) +
  facet_wrap(~country,scales = "free_x")

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.

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