根据 ggplot 中的变量值设置轴限制

elm*_*lmg 2 r ggplot2

我有一个数据框,其中包含程序和程序中每个人的国家/地区。我需要为每个项目制作一个条形图,其中包含每个国家/地区的参与者数量。我包括示例数据和下面的代码。

实际上,我有 20 多个程序,每个国家有数百个条目,并且希望通过仅更改代码中程序的名称来自动化此过程以迭代所有程序。在条形图中,我需要在水平条的外端放置数据标签,但这会将它们打印到绘图窗口的限制之外。为了解决这个问题,我想调整轴的比例,但是我不想为每个程序手动调整它,而是想将限制设置为“计数”变量最大值以上 10%。

我的问题是是否可以使用数据框中的变量值来设置限制,而不是为每个图对它们进行硬编码(并且最好在不保存单独的国家/地区计数表的情况下执行此操作)。如果这不是可以做到的事情,有谁知道有效的替代方法来自动调整轴比例和/或调整绘图窗口以适应标签?

我在其他地方找不到这个问题的答案,但如果已经回答了类似的问题,如果有人能指出我的解决方案,我将不胜感激。

sample_data <- data.frame(
                          "person_number" = 1:15, 
                          "country" = c("United States", "Canada", "India", "United States", "United 
                                         States", "United States", "India", "China", "China", "United 
                                         States", "China", "India", "Canada", "United States", "China"), 
                          "program" = c("Program1", "Program2", "Program3", "Program2", "Program3", 
                                        "Program3", "Program3", "Program2", "Program3", "Program1", 
                                        "Program1", "Program3", "Program1", "Program2", "Program1")
                          )
Run Code Online (Sandbox Code Playgroud)
sample_data %>% 
    filter(program == "Program1") %>% 
    group_by(country) %>% 
    summarise(Count = n_distinct(person_number)) %>% 
    ggplot(aes(x = reorder(country, Count), y = Count)) +
      geom_bar(stat = "identity", fill = "salmon3") +
      coord_flip() +
      labs(title = "Country for Program1 Applicants") +
      geom_text(aes(label=Count), size=3, hjust=-0.2) +
      ylim(0, max(Count)+0.1*max(Count))                     # this line does not work
                                                             # error message: object 'Count' not found
Run Code Online (Sandbox Code Playgroud)

Axe*_*man 6

这正是expand量表中参数的含义。我们可以设置乘法轴扩展。

我们还可以稍微简化您的代码:

sample_data %>% 
  filter(program == "Program1") %>% 
  ggplot(aes(x = forcats::fct_infreq(country))) +
  geom_bar(fill = "salmon3") +
  geom_text(aes(label = stat(count)), stat = 'count', size = 3, hjust = -0.2) +
  labs(title = "Country for Program1 Applicants") +
  scale_y_continuous(expand = expansion(c(0, 0.1))) +
  coord_flip()
Run Code Online (Sandbox Code Playgroud)

我还关闭了绘图左侧的扩展。参见?scale_y_continuous?expansion

在此输入图像描述