ggplot scale_fill_manual通过查找like / wildcard值

问题描述 投票:0回答:2

我正在循环一个函数来计算我校园所有课程中所有学生的比赛,然后汇总他们在课程中收到的比赛和成绩,以创建成绩分布。我也在比赛中粘贴比赛金额(例如,非洲裔美国人(192)),以表明每个种族群体的学生人数。然后,我正在为每个课程绘制数据(600多个课程,因此循环)。我的问题是,当我将scale_fill_manual颜色分配给每个种族类别时,它会失败,因为种族类别从一次迭代变为下一次:第一种可能是非裔美国人(192),第二种可能是非裔美国人(87)所以我无法选择scale_fill_manual值......也就是说,我无法编码

scale_fill_manual(values = c("African American"="violetred1","Asian"="orange3)

因为每个种族群体的名称都在不断变化。所以,我的问题是,是否有一种方法,就像SQL一样,将通配符应用于值...类似于:

scale_fill_manual(values = c("African American*"="violetred1","Asian*"="orange3) 

或者也许有更好的方法来做到这一点?

编辑:我有种族,计数和种族的列,如下所示:

African American, 192, African American (192)

所以,如果有一种方法可以填充racecount所以每个组的图例标签是Race(count),但是然后将scale_fill_manual分配给比赛列,其中组保持不变,这可能有效,但我不知道怎么做发生。

这是一个可重复的例子:

library(tidyverse)
library(extdplyr)
library(pacman)
p_load_gh("trinker/wakefield")
set.seed(10)

df1<-dplyr::data_frame(
  ID = wakefield::id(n=100), 
  Race = race(n=100),
  Course = group(n=100),
  Grade =sample(1:5,100,replace=T))



df1

courselist=list("Treatment","Control")


myplot<-function(coursegrade){

  coursegrade<-as.character(coursegrade)
  subject<-df1%>%filter(Course==coursegrade)
  percents<- pct_routine(subject, Race, Grade)
  dat2 = subject %>%
    group_by(Race) %>%
    summarise(Count = n())
  percents<-inner_join(percents, dat2, by = "Race") 
  percents$Count <- with(percents, paste0("(", Count, ")"))
  percents$Race.Eth <- paste(percents$Race, percents$Count)
  percents$pct<-percents$pct*100

  temp_plot=ggplot(percents,aes(fill=Race.Eth, y=pct, x=Grade)) + 
    geom_bar(position="dodge", stat="identity", colour="black", width = .8) +
    ggtitle("Grade Distributions by Race, 2015 - 2018", subtitle = coursegrade) + 
    theme(plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = .5)) +
    scale_y_continuous(limits=c(0,70)) 



  ggsave(temp_plot, file=paste0(coursegrade," - grade distribution.jpg"), width = 13, height = 7, units = "in")
  print(temp_plot)
}

lapply(courselist,myplot)
r ggplot2 wildcard
2个回答
0
投票

您可以通过将ggplot代码中的标签添加到您真正需要的位置来避免此问题。例如,假设您只在图表的标题中使用它,然后将标签保持为“非洲裔美国人”(因此您可以将其与其颜色相匹配)并使用labs(title = paste0(my_label, " (", my_count, ")")),其中my_label将对应于“非洲裔美国人”和my_count到伯爵。


0
投票

正如@ user2362777所提到的,最好不要在ggplot代码块中执行此标记。在进入gg之前,考虑为“race”创建一个新列或编辑原始列。

您的选择包括:

在SO:https://stackoverflow.com/search?q=%5Br%5D+partial+string+match+replace上还有其他类似的帖子

© www.soinside.com 2019 - 2024. All rights reserved.