如何使x轴垂直,以使国家/地区的长名称在图中变得易于理解

时间:2019-06-03 21:41:20

标签: r ggplot2 data-visualization

国家/地区的名称很长,并且在x标签中彼此重叠,如何使它可读?

ggplot(results, aes(x = Nationality, horiz=TRUE)) +
  theme_solarized() +
  geom_bar() +
  labs(y = "Number of Medals", 
       title = "Number of Medals by Country")

1 个答案:

答案 0 :(得分:0)

欢迎来到stackoverflow。以下是有关如何处理多种价值的一些建议。在这两种方法中,我都使用forcats中的tidyverse库。您可以在这里了解更多信息:https://r4ds.had.co.nz/factors.html

首先,一些虚假数据并复制您的问题

library(tidyverse)

df <-
  mpg %>% 
  arrange(manufacturer) %>% 
  mutate(
    n = row_number(),
    vehicle = paste(year, manufacturer, model)
  ) %>% 
  uncount(n)


# this replicates your problem
ggplot(df, aes(vehicle)) +
  geom_bar() +
  coord_flip()

enter image description here

选项1:合并

df %>% 
  mutate(
    vehicle = # making heavy use of forcats here
      fct_lump(vehicle, 35) %>% # keep only the 35 most frequent values, others in "Other" category
      fct_infreq() %>% # order them by frequency
      fct_rev() #reverse the order
  ) %>% 
  ggplot(aes(vehicle)) +
  geom_bar() +
  coord_flip()

enter image description here

选项2:方面

有人可能会更优雅地吸引这些人,但是我经常使用这种方法

df %>% 
  mutate(
    vehicle = # similar methods to earlier
      fct_infreq(vehicle) %>% 
      fct_rev(),
    num_fct = as.integer(vehicle), # generates a number for each factor
    facet = (max(num_fct)-num_fct) %/% 20 # will make groups of 20, but they need to be in descending order within each facet
  ) %>%
  ggplot(aes(vehicle)) +
  geom_bar() +
  coord_flip() +
  facet_wrap(~facet, scales = "free_y", nrow = 1) +
  theme(
    strip.background = element_blank(),
    strip.text = element_blank()
  )

enter image description here

希望这会有所帮助。