首页 文章

当存在多个geom时,移除一个geom的轴标签

提问于
浏览
0

我想要的只是这个R代码显示“topName”中的玩家名称,同时通过使用两个不同的geom_col()绘制两个名称来隐藏“otherNames”中的名称 .

epldata < - read.csv(file ='epldata.csv')epldata $ srno < - c(1:461)attach(epldata)points < - epldata [order(-fpl_points),] detach(epldata)topNames [24 :461] < - NA epldata $ topNames < - topNames topPoints [24:461] < - NA epldata $ topPoints < - topPoints epldata $ otherNames < - NA epldata $ otherNames [24:461] < - as.character(points $ name [c(24:461)])epldata $ otherPoints < - NA epldata $ otherPoints [24:461] < - as.numeric(points $ fpl_points [c(24:461)])ggplot(data = epldata)geom_col(aes (x = epldata $ topNames,y = epldata $ topPoints),fill =“red”,alpha = 1)theme(axis.text.x = element_text(angle = 90,hjust = 1))annotate(“text”,x = epldata $ topNames,y = -50,#epldata $ topPoints,label = epldata $ topNames,fontface = 1,size = 2,hjust = 0)geom_col(aes(x = epldata $ otherNames,y = epldata $ otherPoints), fill =“gray”,alpha = 0.3)theme(legend.position =“none”)#theme(axis.text.x = element_text(angle = 90,hjust = 1))xlab(“Player Names”)ylab(“ FPL Points“)指南(fill = FALSE,color = FALSE,guide = FALSE)coord _flip()主题(axis.text.y = element_blank(),axis.ticks.y = element_blank())

My output image here

This is the kind of output I am looking for但没有使用我目前正在使用的Annotate Hack,而是直接在轴上绘制名称 .

更新:添加了整个代码,数据集的链接如下:https://drive.google.com/open?id=1KTitWDcLIBmeBsz8mLcHXDIyhQLZnlhS

1 回答

  • 0

    创建topNames列表后,可以使用 scale_x_continuous 仅显示这些轴标签:

    scale_x_discrete(breaks = topNames)
    

    此外,您可以在数据框中创建一个新的"highlight"列,而不是使用两个单独的 geom_col() 列,并将其与填充和alpha美学结合使用:

    library(dplyr)
    library(ggplot2)
    
    # read data from google drive
    id <- "1KTitWDcLIBmeBsz8mLcHXDIyhQLZnlhS" #google file ID
    epldata <- read.csv(sprintf("https://docs.google.com/uc?id=%s&export=download", id),
                        stringsAsFactors = FALSE)
    
    N <- 24 #number of players to highlight
    
    #get list of names of top N players
    topNames <- epldata %>% 
      arrange(-fpl_points) %>% 
      head(N) %>% 
      pull(name)
    #> Warning: package 'bindrcpp' was built under R version 3.5.1
    
    # make variable for highlighting
    epldata <- epldata %>% 
      mutate(highlight = ifelse(name %in% topNames, TRUE, FALSE))
    
    ggplot(data = epldata,
           aes(x = name, y = fpl_points, fill = highlight, alpha = highlight)) +
      geom_col() +
      scale_fill_manual(guide = FALSE,
                        values = c("gray", "red")) +
      scale_alpha_manual(guide = FALSE,
                         values = c(0.4, 1)) +
      scale_x_discrete(breaks = topNames) + #use breaks to determine axis labels
      coord_flip() +
      ylab("FPL Points") +
      theme_classic() +
      theme(axis.ticks.y = element_blank(),
           axis.title.y = element_blank())
    

    由reprex包创建于2018-09-19(v0.2.1)

    including only some axis labels

相关问题