用%变化趋势线绘制geom_col

时间:2020-07-29 01:50:02

标签: r ggplot2

我试图在ggplot enter image description here

上绘制与此图像相似的图像

我该怎么做?我在将轴设置为仅显示一个值时遇到麻烦。到目前为止,这是我尝试过的。

# A tibble: 5 x 3
  Values  Year  change
   <dbl> <dbl>   <dbl>
1  12307  1999   NA   
2   6267  2000  -96.4 
3   6119  2001   -2.42
4   9254  2002   33.9 
5   3124  2003 -196.   

ggplot(df) +
  geom_col(aes(x= Year, y = Values)) +
  geom_line(aes(x= Year, y = change))

2 个答案:

答案 0 :(得分:3)

我完全同意这里提出的所有问题,涉及到具有次要y轴的情节的可解释性。应始终避免使用IMO辅助轴。

也就是说,ggplot允许您使用辅助y轴;所有要做的就是在辅助轴(此处为change)上缩放数据,并在sec.axis内部使用反向转换。通过简单的线性模型y_scaled = a0 + a1 * y_original给出转换。

这里是重现情节的尝试:

a1 <- (0 - max(df$Values, na.rm = TRUE) / (diff(-range(df$change, na.rm = TRUE))))
a0 <- max(df$Values, na.rm = TRUE) - a1 * max(df$change, na.rm = TRUE)


library(hrbrthemes)   # For dark ggplot theme
library(tidyverse)    # For ggplot and dplyr
df %>%
    mutate(change_scaled = a0 + a1 * change) %>%
    ggplot(aes(Year, Values)) +
    geom_col(fill = "#00D987", colour = NA) +
    geom_text(
        aes(y = Values, label = Values),
        colour = "#00D987",
        vjust = -1) +
    scale_y_continuous(
        limits = c(0, 1.1 * max(df$Values)),
        sec.axis = sec_axis(~ (. - a0) / a1,name = "Change")) +
    geom_point(
        aes(x = Year, y = change_scaled, group = 1), colour = "#FE9E00") +
    geom_line(
        aes(x = Year, y = change_scaled, group = 1), colour = "#FE9E00") +
    theme_ft_rc() +
    theme(
        axis.title.y = element_text(color = "#00D987"),
        axis.title.y.right = element_text(color = "#FE9E00"))

enter image description here


样本数据

df <- read.table(text = " Values  Year  change
12307  1999   NA
 6267  2000  -96.4
 6119  2001   -2.42
 9254  2002   33.9
 3124  2003 -196.
", header = T)

答案 1 :(得分:2)

这可能是您的最佳选择,因为所需的可视化从根本上来说并不理想。这将有助于您的查看者看到这种关系,但是您也可以查看其他有助于显示这三个变量之间关系的可视化效果

   readin <- "  Values  Year  change
1  12307  1999   0   
2   6267  2000  -96.4 
3   6119  2001   -2.42
4   9254  2002   33.9 
5   3124  2003 -196.0  "

df <- read.table(text = readin, header = TRUE)

library(ggplot2)
library(gridExtra)

p1 <- ggplot(df) + aes(x= Year, y = Values, label = Values) +    geom_col() + geom_text(vjust = -0.5)

p2 <- ggplot(df) + aes(x= Year, y = change, label = change) +    geom_line() + geom_text(vjust = -0.5)


grid.arrange(p1, p2, nrow=1, ncol=2)

enter image description here