【问题标题】:color datapoints according to specific value in a column根据列中的特定值为数据点着色
【发布时间】:2020-12-09 16:09:27
【问题描述】:
df <- data.frame(col1=c('hio.k2','fhuei.k1','buew.k2'),col2=c(1,4,5.5))
> df
      col1 col2
1   hio.k2  1.0
2 fhuei.k1  4.0
3  buew.k2  5.5

我想绘制 df 并为数据分配颜色。着色组在col1 中定义.k1.k2。 我试过了

color = rep(NA, length=length(df$col2))
color[which(df$col2=="*k1")] = "red"
color[which(df$col2=="*k2"))] = "blue"

这是行不通的。我认为问题是*。如何根据k1k2 中的col1 分配颜色?

我希望颜色看起来像这样

color
'blue','red','blue'

为了剧情

hist <- ggplot(df) + 
  geom_histogram(mapping = aes(x = `col2`),show.legend = TRUE,color = color) +
  

【问题讨论】:

  • 你想做什么情节?
  • 我在剧情中添加了信息。@Edo

标签: r plot colors


【解决方案1】:

这是您需要的条形图。 (我猜你的意思是条形图而不是直方图)

library(ggplot2)


ggplot(df) +
    geom_col(aes(x = col1, y = col2, fill = stringr::str_sub(col1, -2, -1))) +
    scale_fill_manual(values = c(k2 = "blue", k1 = "red")) +
    labs(fill = "K")

不过,我相信默认颜色更好:

ggplot(df) +
    geom_col(aes(x = col1, y = col2, fill = stringr::str_sub(col1, -2, -1))) +
    labs(fill = "K") +
    theme_light()

【讨论】:

  • 也可以使用正则表达式fill = sub('.*\\.(.*$)', '\\1', col1)
【解决方案2】:

我建议这种方法使用来自tidyverseggplot2 和一些数据操作来获取颜色变量:

library(tidyverse)
#Data
df <- data.frame(col1=c('hio.k2','fhuei.k1','buew.k2'),col2=c(1,4,5.5))
#Separate and create bar
df %>% mutate(dup=col1) %>% separate(col = dup,into = c('dup','coln'),sep = '\\.') %>%
  select(-dup) %>%
  ggplot()+
  geom_point(aes(x=col1,y=col2,color=coln))+
  scale_color_manual(values = c('k1'='red','k2'='blue'))+
  theme_bw()

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 2016-11-04
    • 2019-02-16
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多