【问题标题】:customize categorical axis labels (allowing duplicated labels) in ggplot在ggplot中自定义分类轴标签(允许重复标签)
【发布时间】:2020-11-02 14:36:36
【问题描述】:

我想基于具有分类 X 轴和要绘制的多种类型元素的数据框构建图,并且应该只将某些记录放置在图上:

dt1 <- fread('
    ID label   type value
    a1     A    bar   40 
    a1     A  point   30 
    b1     B    bar   50 
    b1     B  point   20 
    c1     C    bar   30 
    c1     C  point   45 
    c1     C  point   20 
    d1     D  point   30 
    d1     D  point   35 
    e1     E   none   50 
    a2     A    bar   45 
    a2     A  point   30 
    ')

# I want some custom order on the plot,
# here it will be   b1 - c1 - a1 - d1 - a2
dt1[, ID:=factor(ID, levels=unique(ID[order(value)]))]

(在这个示例数据集中,我只显示“点”和“条”,但在真实的数据集中,我有更多元素和额外的列来决定是否绘制它们)

我想要的情节应该是这样的:
您可以看到标签取自我数据框中的另一列,但它们不是唯一的,所以我不能简单地使用aes(x=label)。我想我应该添加类似scale_x_discrete(labels=???) 的内容,但不确定我应该放什么。
一般来说,我实际上对两种不同类型的解决方案感兴趣:a)将标签映射到原始数据集的另一列; b) 以某种方式从 ggplot 对象中提取“内部”标签并用gsub()toupper() 等简单的东西处理它们。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以将函数传递给scale_x_discrete()labels 参数:

    library(ggplot2)
    library(data.table)
    
    dt2 <- dt1[type != "none"]
    dt2[, ID:=factor(ID, levels=unique(ID[order(value)]))]
    
    ggplot(dt2, aes(x=ID,y=value))+
      geom_col(data=dt1[type=='bar',], alpha=0.5) +
      geom_point(data=dt1[type=='point',], size=5, col='red') +
      scale_x_discrete(limits = levels(dt2$ID), labels = function(x) dt2$label[match(x, dt2$ID)])
    

    要回答您的第二点,给定 x 轴的当前值,您还可以使用以下内容:

    scale_x_discrete(limits = levels(dt2$ID), labels = function(x) gsub("[[:digit:]]", "", toupper(x)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2021-11-04
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      相关资源
      最近更新 更多