【问题标题】:Assigning fixed ggplot2 shapes based on dynamic set of values根据动态值集分配固定的 ggplot2 形状
【发布时间】:2018-07-23 18:24:30
【问题描述】:

我正在处理一个 Power BI 项目,并且正在制作一些 R 视觉效果。其中一个视觉效果是散点图。每个点都有一个分类值(“是”、“否”)。我选择通过形状来表示这些类别。有时用户会以每个点只有一个类别的方式查询数据。我希望我的“是”形状仅对“是”值保持唯一,而“否”形状仅对“否”值保持唯一。

我的代码:

ggplot(data = dataset) + 
    geom_point(data = dataset, aes(x= value1 y=value2, shape = YesNo_column) + 
    scale_shape_manual(name="", values = c(20, 0))

我希望“是”点始终具有形状“20”,而“否”点始终具有形状“0”。如果用户查询数据只显示“No”点,那么我的代码会将形状“20”分配给这些点,而不是形状“0”。

编辑:我刚刚制作了一些示例数据来显示我的问题:

query1 <- mtcars[mtcars$cyl == 4 | mtcars$cyl == 6,]

query1$YesNo_column <- "blah"

query1[query1$cyl==4,]$YesNo_column <- "Yes"
query1[query1$cyl==6,]$YesNo_column <- "No"


ggplot(query1, aes(x=mpg, y=hp, shape=YesNo_column)) + 
  geom_point()+
  scale_shape_manual(name="",values = c(20, 0))


query2 <- query1[query1$YesNo_column == "Yes",]

ggplot(query2, aes(x=mpg, y=hp, shape=YesNo_column)) + 
  geom_point()+
  scale_shape_manual(name="",values = c(20, 0))

如您所见,形状并不固定为值。

【问题讨论】:

    标签: r ggplot2 powerbi


    【解决方案1】:

    确保您的 yesno 被编码为一个因子,并且只需使用 DROP = FALSE

    library(tidyverse)
    
    mydata <- tibble(
      x = rnorm(20, 1.0, 0.3),
      y = rnorm(20, 1.5, 0.4),
      response = sample(c("yes", "no"), replace = TRUE, size = 20)
    ) %>% 
      mutate(response = as.factor(response))
    
    
    ggplot(mydata, aes(x = x, y = y, shape = response)) + 
      geom_point() + 
      scale_shape_manual(name="", values = c(20, 0), drop = FALSE)
    
    mydata %>%
      filter(response == "yes") %>% 
      ggplot(aes(x = x, y = y, shape = response)) + 
      geom_point() + 
      scale_shape_manual(name="", values = c(20, 0), drop = FALSE)
    

    【讨论】:

      猜你喜欢
      • 2018-02-05
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2020-07-03
      相关资源
      最近更新 更多