R语言 ggplot2:根据辅助y轴的范围移动重叠点

xfb7svmp  于 2023-05-20  发布在  其他
关注(0)|答案(1)|浏览(160)

左手侧y轴的范围从0到5000左右,右手侧从0到600。对于scale_y_continuous(sec.axis = sec_axis(~. * 0.2, name = "price")),我想将点向上移动,但它们现在似乎在0-5000范围内,所以它们都在底部。
How to link the secondary y-axis to the correct variable in ggplot2?的这一行没有帮助。

scale_y_continuous(
    name="Price",
    sec.axis=sec_axis(trans=~ . * 0.2, 
                      name="Price")
  )

如何更改代码?谢谢

library(ggplot2)
library(tidyverse)

price.avg <- diamonds %>%
  group_by(cut, color) %>%
  summarise(price = 0.1 * mean(price), dummy = "1")

summary(price.avg)
        cut    color     price          dummy          
 Fair     :7   D:5   Min.   :259.8   Length:35         
 Good     :7   E:5   1st Qu.:358.5   Class :character  
 Very Good:7   F:5   Median :423.9   Mode  :character  
 Premium  :7   G:5   Mean   :421.4                     
 Ideal    :7   H:5   3rd Qu.:480.2                     
               I:5   Max.   :629.5                     
               J:5            

   

diamonds %>%
  ggplot() +
  geom_bar(aes(x = cut, fill = clarity)) +
  facet_wrap(~ color) +
  ylab("Count") +
  xlab("Cut") + 
  geom_point(data = price.avg, aes(x = cut, y = price, col = "")) +
  scale_y_continuous(sec.axis = sec_axis(~. * 0.2, name = "price")) + 
  scale_color_manual(name = "", label = "Average price", values = "black")

kqhtkvqz

kqhtkvqz1#

改变规模是不够的。您还必须使用逆变换来变换数据,即在geom_point中使用y = price / .2

library(tidyverse)

price.avg <- diamonds %>%
  group_by(cut, color) %>%
  summarise(price = 0.1 * mean(price), dummy = "1")
#> `summarise()` has grouped output by 'cut'. You can override using the `.groups`
#> argument.

diamonds %>%
  ggplot() +
  geom_bar(aes(x = cut, fill = clarity)) +
  facet_wrap(~ color) +
  ylab("Count") +
  xlab("Cut") + 
  geom_point(data = price.avg, aes(x = cut, y = price / .2, col = "")) +
  scale_y_continuous(sec.axis = sec_axis(~. * 0.2, name = "price")) + 
  scale_color_manual(name = "", label = "Average price", values = "black")

相关问题