【问题标题】:Change the colour of a subset of labels in barplot R更改 barplot R 中标签子集的颜色
【发布时间】:2018-11-17 07:49:18
【问题描述】:

我正在尝试调整我的条形图,以便只有少数标签以不同的颜色显示。我知道之前有一个类似的问题 (Change the color of a subset of group labels in a boxplot in R),但答案对我没有帮助,我在网上找到的所有其他内容也没有,所以我真的非常感谢一些帮助。

我的数据如下所示:

trait2 <- c('A','B','C','D')
rg <- c (0.5480, 0.4801, 0.2805, -0.2480)
se <- c(0.0495, 0.0908, 0.0548, 0.0957)
data <- data.frame(trait2,rg,se)
data
 trait2   rg      se
 A       0.5480  0.0495
 B       0.4801  0.0908
 C       0.2805  0.0548
 D       -0.2480  0.0957

条形图的代码如下所示:

barplot1 <- barplot(data$rg,
main="correlation between traits",
xlab="rG",  
border="blue", 
las=1, 
horiz=TRUE, 
names.arg=data$trait2, 
font.axis=2
cex.names=0.5,
xlim=range(-0.4,0.6,0.1) )

我现在想更改 A 和 C 的标签颜色,但 B 和 D 应该保持黑色。

我试过这个,正如我在上面提到的链接中描述的那样:

mtext(barplot1$trait2, at = 1:length(barplot1$trait2, side=1, line=1,  
col=ifelse(barplot$trait1=="A", "red", "black")))

然后我收到错误“barplot$trait2 中的错误:$ 运算符对原子向量无效。这是有道理的,但我仍然不知道如何解决它。

还有一个使用的建议

 + scale_colour_manual(values = c("B" = "red"))

我真的无法理解。 (我应该在哪里插入?)

希望有人能帮助我,在此先感谢!

【问题讨论】:

  • scale_colour_manual()ggplot2 包中的一个函数。该软件包为您提供了更灵活的图表创建方式。

标签: r plot colors label customization


【解决方案1】:

使用ggplot 比内置绘图库更容易、更优雅。 scale_color_manualscale_fill_manual 可以插入到 ggplot 代码中。在此处阅读 (http://r4ds.had.co.nz/data-visualisation.html)。

这是一个为条形着色的示例。

library(tidyverse) #this package contains many other useful packages included ggplot    

data <- tibble(total = c(5, 6, 4, 3), month = c("april", "may", "june", "july")  
# tibble is used to create a type of data.frame object.

ggplot(data = data, aes(x = month, y = total, fill = type)) +
  geom_col()  

改变颜色的是“填充”参数。 "color" 参数用于图形对象,如线和点。

【讨论】:

    【解决方案2】:

    你可以试试

    barplot1 <- barplot(data$rg,
                        main="correlation between traits",
                        xlab="rG",  
                        border="blue", 
                        las=1, 
                        horiz=TRUE, 
                        font.axis=2,
                        cex.names=0.5,
                        xlim=range(-0.4,0.6,0.1))
    
    axis(2, at = barplot1[c(1,3)], labels = data$trait2[c(1,3)], col.axis = 2)
    axis(2, at = barplot1[c(2,4)], labels = data$trait2[c(2,4)], col.axis = 1)
    

    在ggplot中你可以试试

     ggplot(data, aes(trait2, rg)) + 
       geom_col(colour="blue", fill="grey") +
       coord_flip() +
       theme_bw() +
       theme(axis.text.y = element_text(colour = rep(c(2,1),2), size=20))
    

    【讨论】:

    • 嗨!非常感谢!!使用“las=1”参数,我还在 barplot() 示例中将标签旋转了 90°。在我的真实数据中,标签实际上比单个字母长得多(为了简单起见,我只发布了这样的示例)。在我在 barplot 函数中使用“cex.names=0.5”调整标签的大小之前。使用axis()似乎不起作用。你知道如何用axis()调整字体大小吗?而且我知道,我可能应该切换到 ggplot2,我只是在安装它时遇到了一些问题,这就是我现在坚持使用 barplot() 的原因。
    • @Nora try cex.axis=2 设置标签的大小
    猜你喜欢
    • 2015-04-07
    • 2019-06-08
    • 2021-03-17
    • 2020-12-26
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    相关资源
    最近更新 更多