【问题标题】:How to assign the same colors to duplicate values using plot() function in R?如何使用 R 中的 plot() 函数为重复值分配相同的颜色?
【发布时间】:2020-08-20 07:10:15
【问题描述】:

我有一个包含 4 列的数据框。我正在绘制由“距离”列着色的总车祸与总损失。我能够生成彩色图。但是,当我检查情节时,我发现情节并没有按照应有的方式着色。由于有许多重复的距离值,我通过距离列的唯一值创建了一个调色板。然后将其作为颜色分配给图例和 plot()。但是检查绘图颜色是不正确的。例如距离 600 在图例中用黄色着色,但相应的点用红色着色。我认为问题是我需要创建一个与数据框中实例数一样多的颜色,即 58。但我有重复的值,它们最初没有排序。基本上我需要从最低距离到最高距离的颜色随着增加与崩溃和损失数据正确匹配的颜色阴影。 下面是最小的可重现数据框和我的代码,但有缺陷。

# creating dataframe
year <- data.frame(year = seq(1946,2003,1))
crashes <- data.frame(crashes = c(386,317,294,287,266,245,268,296,226,265,243,239,183,212,195,224,170,169,140, 147,111,119,100,115,128,111,80,77,68,69,84,72,90,82,59,67,45,59,50,64,55,63,56,56,57,68,34,32,26,21,20,30,35,28  ,22,27,34,NA))
losses <- data.frame(losses = c(432,423,341,291,282,288,387,323,229,305,244,333,200,215,211,245,197,177,153,152, 115,189,124,129,133,120,91,90,69,78,88,77,95,98,62,70,45,62,70,68,65,73,90,65,61,74,39,33,31,22,21,39,35,58,25,36 ,40,NA))
distance <- data.frame(distance = c(600,571,589,613,618,605,605,610,608,584,605,615,605,597,603,600,578,560,541,500,478,459,449,447,452,444,431,433,452,436,426,425,430,426,430,417,372,401,389,418,414,397,443,436,431,439,430,425,415,423,437,463,487,505,503,508,516,529))
df <- cbind(year,crashes,losses,distance)
palette <- heat.colors(length(unique(df[order(df$distance),]$distance)))
plot(df$crashes,df$losses, main = "Crashes,Losses and Distance",xlab = "Crashes", ylab = "Losses", col = palette)
#legend
legend(x = 401,y = 450, legend = unique(df[order(df$distance),]$distance) , cex=.3, fill = palette, xpd=TRUE)

【问题讨论】:

  • 这可能会有所帮助:stackoverflow.com/questions/17551193/…。您的颜色向量需要与 x 和 y 向量的长度相同,并且应该为每个点提供颜色,而不仅仅是您要使用的颜色列表。
  • @MrFlick 我觉得手动过滤总共 58 个值和 47 个唯一值需要很长时间
  • 嗯,它不需要手动过程。您确定要使用基础 R 吗?使用 ggplot 可能会更容易。
  • @MrFlick 最好使用 plot() 函数。你有什么建议?

标签: r plot


【解决方案1】:

嗨,据我了解,您正在尝试为每个距离赋予独特的颜色,这很容易,但我强烈建议您首先为距离添加一个分组字符因子,而不是使用 47 个独特的距离级别( numerics > 这将产生 47 种不同的颜色,如果你使用:'distance' 而不是:'distance_new' 在下面)

这是我的代码:

# same df as you posted:
df <- cbind(year,crashes,losses,distance)

# this is necessary if you would want to use 'distance' for coloring
df$distance<- as.factor(df$distance) 

## imo better add a grouping factor distance_new 
## (this is automatically stored as class factor)

df$distance_new<-cut(as.numeric(df$distance),4, labels = c("very low","low","medium","high"))

# Now the plot
plot(df$crashes,df$losses, main = "Crashes,Losses and Distance",
xlab = "Crashes", ylab = "Losses",
col = df$distance_new, pch =19)

# add a legend
legend("bottomright",legend = unique(df$distance_new ),
fill=unique(df$distance_new), cex= 0.5, title= "Distance")
View(df)


【讨论】:

  • 这与我要求的方式不同,但是如果我想保留距离值而不是将它们分组到类别中怎么办?
  • 它的工作原理相同,只需使用:'distance'(必须是一个因素),而不是:'distance_new'
猜你喜欢
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多