【问题标题】:Using r and ggplot How do I specify specific hexadecimal color/colour values to use to represent different character values使用 r 和 ggplot 如何指定特定的十六进制颜色/颜色值来表示不同的字符值
【发布时间】:2015-09-27 19:09:25
【问题描述】:

假设 is.character(MyColours) = TRUE 其中 MyColours 包含许多十六进制颜色值。

如何确保当我想使用 ggplot 绘图时,我可以确保 MyColours[1] 将始终用于表示“Ford”,而 MyColour[3] 在我无法保证订单时将表示“Toyota” “福特”或“丰田”将出现在我用来绘制的观察结果中。

虽然下面的 geo_bar 示例很有帮助,并且确实提醒我将列名添加到 MyColours,但我希望绘制线条而不是条形

    ggplot(MyData, aes(x = TimePeriod, y = CountOfItems, 
group = Account, color = scale_fill_manual(values = MyColours))) 
    + geom_line(size = 1) 
    + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

即使length(MyColours) 等于length(unique(MyData$Account)),我也会收到错误Aesthetics must either be length one, or the same length as the dataProblems:scale_fill_manual(values = MyColours)

样本数据

dput(MyData)
structure(list(Account = structure(c(1L, 2L, 1L, 2L), .Label = c("Mazda RX4", 
"Toyota Corolla"), class = "factor"), CountOfItems = c(14, 120, 
23, 345), TimePeriod = structure(c(1L, 2L, 2L, 3L), .Label = c("2010-12", 
"2011-01", "2011-02"), class = "factor")), .Names = c("Account", 
"CountOfItems", "TimePeriod"), row.names = c(NA, -4L), class = "data.frame")

是否可以将 scale_fill_manual 与线图一起使用?

【问题讨论】:

标签: r colors ggplot2 hex


【解决方案1】:

您可以命名MyColours,例如像这样:

MyColour <- c("#FF0000", "#00FF00", "#0000FF") 
names(MyColour) <- c("Mazda RX4", "Toyota Corolla", "Fiat 128")

df <- mtcars[c("Mazda RX4", "Toyota Corolla", "Fiat 128"), ]
df$car <- rownames(df)
library(ggplot2)
ggplot(df, aes(x = car, y = mpg, fill = car)) +
  geom_bar(stat = "identity") + 
  scale_fill_manual(values = MyColour)

【讨论】:

  • 编辑您的帖子并添加可重现的示例。
  • 更新了问题,但仍在学习 R 和 stackoverflow,因此对于忘记降价表示歉意。
  • 没问题。我想每个人都在这里经历了那个学习过程。当我运行你的代码时,我得到 - 除了其他错误 - Error in ggplot(MyData, aes(x = TimePeriod, y = CountOfItems, group = Account, : object 'MyData' not found。请添加它 - 或类似的数据集。我提供的链接显示了如何。
  • 添加了示例数据,我想将数据图中的线条着色为MyColour,因此马自达 RX4 将使用 #FF0000 作为线条颜色
  • 试试ggplot(MyData, aes(x = TimePeriod, y = CountOfItems, group = Account, color = Account)) + geom_line(size = 1) + scale_color_manual(values = MyColours)
猜你喜欢
  • 2014-08-07
  • 2019-07-08
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多