【问题标题】:is there a function in r to have scatterplot data on the same scale? [closed]r 中是否有一个函数可以让散点图数据具有相同的比例? [关闭]
【发布时间】:2022-01-20 01:42:23
【问题描述】:

我已经在 r 并排视图上制作了一个散点图,并且很难在相同的比例上得到它,有没有办法简单地做到这一点?都在 15-30 的 y 轴刻度上

这是我目前的代码

p1 <- ggplot(covid, aes(x=covid1$oct2019_rent, y=covid1$Depression.2019))+ geom_point()+ ggtitle("Depression Rates Vs Rise in Rent")+ xlab("October 2019 Rent")+ ylab("Depression 2019")

p2 <- ggplot(covid, aes(x=covid1$oct2020_rent, y=covid1$Depression.2020)) + geom_point()+
  xlab("October 2020 Rent")+
  ylab("Depression 2020") 

p1 + p2

这是我的数据的样子

【问题讨论】:

  • 在两个图中添加+ scale_y_continuous(limits = c(15, 30))
  • 而且,仅供参考,不要将data$column 放在aes() 中——这就是data 参数的用途。简化为ggplot(covid, aes(x = oct2020_rent, y = Depression.2020))
  • 不知道用facet_wrapfacet_grid会不会更方便

标签: r ggplot2 scale scatter-plot


【解决方案1】:

正如@Zhiqiang Wang 所建议的那样,使用facet_wrap 让您的生活更轻松,特别是如果您将来有可能不在所需的15-30 范围内的新数据(否则@Gregor Thomas 解决方案是最简单的方法走)。但是,为此您必须稍微修改您的数据:

library(tidyverse)

# dummy data
df <- tibble(Depression.2019 = runif(100) * 40,
             oct2019_rent = runif(100) * 3500,
             Depression.2020 = runif(100) * 40,
             oct2020_rent = runif(100) * 3500) 

# split up original data, "lengthen" your data and extract year values
df1 <- df %>% select(starts_with("Depr")) %>%
  pivot_longer(everything(),
               names_to = "year",
               values_to = "Depression") %>%
    mutate(year = str_extract(year, "\\d+"))

df2 <- df %>% select(starts_with("oct")) %>%
  pivot_longer(everything(),
               names_to = "year",
               values_to = "Rent") %>%
  select(-year)

# plot using facet_wrap
df1 %>% bind_cols(df2) %>%
  ggplot(aes(Rent, Depression)) +
  geom_point() +
  facet_wrap(~year) +
  ggtitle("Depression Rates Vs Rise in Rent")

【讨论】:

  • @GregorThomas 虽然将limits 添加到scale_xxx_yyy 调用在这里有效,但我觉得这是一个危险的习惯,因为在计算汇总统计数据时会产生副作用。我建议改用coord_cartesian,因为它不会冒副作用的风险。 here 提出的问题就是一个很好的例子。我的附加评论 4 解释了 limitscoord_cartesian 之间的区别。
猜你喜欢
  • 2020-06-24
  • 1970-01-01
  • 2011-02-05
  • 2021-01-07
  • 1970-01-01
  • 1970-01-01
  • 2013-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多