【问题标题】:Setting axes limits based on variable values in ggplot根据 ggplot 中的变量值设置轴限制
【发布时间】:2020-01-09 16:03:23
【问题描述】:

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

实际上,我有 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")
                          )
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

【问题讨论】:

  • 尝试将您的 y 轴限制设置为 coord_flip(ylim = c(0, max(Count)+0.1*max(Count)))
  • @M_Shimal 我收到一条错误消息,提示“找不到对象'计数'”
  • 是的,我在评论中的解决方案实际上是错误的。它不承认计数。您也许应该在 ggplot 之外执行 max() 并将其作为向量包含在其中。

标签: r ggplot2


【解决方案1】:

这正是比例中的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()

我还关闭了情节左侧的扩展。请参阅?scale_y_continuous?expansion

【讨论】:

  • 非常有用的答案。 expand_scale() 已弃用;请改用expansion()
猜你喜欢
  • 1970-01-01
  • 2023-03-30
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多