【问题标题】:geom_path() Scatterplot ggplot2geom_path() 散点图 ggplot2
【发布时间】:2020-10-23 17:45:58
【问题描述】:

我正在尝试创建一个类似于one 的连接散点图,这有更多explanation

基本上,我试图在一张图表上显示劳动力中人数的下降,以人数衡量。第二张图将显示同一时期内失业率的变化。

这是我的代码:

# ggplot2 call:
Unemployment_Outflows %>%
  ggplot( aes(x=unemployment_rate, y=labor, label=year)) +
  # Custom the Y scales:
  scale_y_continuous() +
geom_line( color="grey") +
    geom_point(shape=21, color="black", fill="#69b3a2", size=3)
  geom_segment(aes(
                    xend=c(tail(unemployment_rate, n=-1), NA), 
                    yend=c(tail(labor, n=-1), NA)
                  )
      ) 

但是,如您所见,线条和阴影区域均不可见,并且出现以下错误:

“geom_path:每个组只包含一个观察值。是否需要调整组审美?”

年 改变 change_perc 失业率 劳动

*年 (chr) 劳动力失业率 (dbl) (dbl)

2015 年第四季度 8416681 0 NA
2016 年第四季度 8492965 12.34717
2017年第四季度 7907511 12.83452
2018年第四季度 6895514 12.74767
2019年第四季度 6437891 12.01787
2020 年第三季度 6409070 15.44732

【问题讨论】:

    标签: r ggplot2 data-visualization tidyverse scatter-plot


    【解决方案1】:

    尝试添加geom_text()。由于未包含任何数据,因此未共享输出。代码如下:

    library(ggplot2)
    library(dplyr)
    #Code
    Unemployment_Outflows %>%
      ggplot( aes(x=unemployment_rate, y=labor, label=year)) +
      # Custom the Y scales:
      scale_y_continuous() +
      geom_line( color="grey") +
      geom_point(shape=21, color="black", fill="#69b3a2", size=3)
    geom_segment(aes(
      xend=c(tail(unemployment_rate, n=-1), NA), 
      yend=c(tail(labor, n=-1), NA)
    )
    )+geom_text(vjust=0.5,fontface='bold')
    

    使用您共享的数据,试试这个:

    library(tidyverse)
    #Code
    df %>% 
      mutate(year=factor(year,levels = unique(year),ordered = T)) %>%
      pivot_longer(-1) %>%
      ggplot(aes(x=year,y=value,color=name,group=name))+
      geom_point()+geom_line()+geom_area(aes(fill=name),alpha=0.5)+
      facet_wrap(.~name,scales='free',nrow = 1)+
      scale_y_continuous(labels = scales::comma)+
      theme_bw()+
      theme(legend.position = 'top')+
      labs(color='Var',fill='Var')
    

    输出:

    使用的一些数据:

    #Data
    df <- structure(list(year = c("Q4 2015", "Q4 2016", "Q4 2017", "Q4 2018", 
    "Q4 2019", "Q3 2020"), labor = c(8416681, 8492965, 7907511, 6895514, 
    6437891, 6409070), unemployment_rate = c(0, 12.34717, 12.83452, 
    12.74767, 12.01787, 15.44732)), class = "data.frame", row.names = c(NA, 
    -6L))
    

    【讨论】:

    • @maa425 看起来是其他包的问题,​​尝试重新启动一个新会话,只加载ggplot2dplyr 然后运行代码!
    • @maa425 还将这一行 ggplot( aes(x=unemployment_rate, y=labor, label=year)) 更改为 ggplot( aes(x=unemployment_rate, y=labor, label=year,group=1))
    • @maa425 试试这个更改ggplot( aes(x=unemployment_rate, y=labor, label=year,group=year)) 让我知道这是否有效!
    • @maa425 我需要数据,使用dput(head(Unemployment_Outflows,100)) 并将输出粘贴到您的问题中,进行编辑。还将颜色更改为black。没有数据我帮不了你!
    • @maa425 我添加了一个更新,请检查它是否适合你!
    猜你喜欢
    • 2019-07-19
    • 1970-01-01
    • 2023-03-09
    • 2010-12-21
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    相关资源
    最近更新 更多