【问题标题】:How to add custom text to a bar-plot dependant on y-axis values in R?如何根据 R 中的 y 轴值将自定义文本添加到条形图中?
【发布时间】:2016-08-24 17:02:44
【问题描述】:

我有以下条形图,我希望为具有 4 个或更多植物物种的所有水平条生成文本标签。颜色代表植物科,因此我希望文本标签显示这些(大约 5 个)植物科的名称(因为很明显,显示 40 多个植物科的图例将是纯粹的混乱)。我可以手动输入姓氏,但它们需要对应正确的水平条。有谁知道我该怎么做?

这是我的情节的代码:

bp2<-barplot(Table2, xlab=c("Fruit Type"), ylab=c("Number of Plant Species"), col=rainbow(45), ylim=c(0,10), beside=T)

我知道放置文本标签类似于:

text(bp2, Table2, labels=Table2, pos=3)

但显然不适合我希望完成的任务。

【问题讨论】:

    标签: r plot bar-chart


    【解决方案1】:

    如果你能提供一个可重现的例子会更好。 例如:

    a<- data.frame(iris[,2])
    row.names(a) <- paste("species-", 1:150, sep= "")
    

    现在您可以选择要显示的 row.names:

    barplot(a[,1], names.arg=ifelse(a[,1] > 4, row.names(a), NA) , las =3)
    

    这将只显示 a 的值大于 4 的名称。

    【讨论】:

      【解决方案2】:

      我找到了一种“足够好”的方法来解决我的问题。代码是:

      text(X, Y, "Custom Label")
      text(X, Y, "Another Custom Label") 
      

      等等。

      只需要知道您希望为其提供自定义标签的水平条的 x,y 坐标。简单的代码很简单!

      编辑:我使用的最终代码和最终产品:

      bp2<-barplot(Table2, xlab=c("Fruit Type"), ylab=c("Number of Plant Species"), col=rainbow(45), ylim=c(0,10), beside=T)
      text(20, 9, "Clusiaceae", pos=3)
      text(30, 8, "Lauraceae", pos=3)
      text(55, 7.5, "Rubiaceae", pos=3)
      text(65, 4, "Fabaceae", pos=3)
      text(120, 4, "Moraceae", pos=3)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-28
        • 1970-01-01
        • 1970-01-01
        • 2014-12-07
        相关资源
        最近更新 更多