簡體   English   中英

R:使用scale_fill_manual更改ggplot填充顏色的問題

[英]R: Issues changing ggplot fill colors with scale_fill_manual

繼Cookbook for R( http://www.cookbook-r.com/Graphs/Legends_ (ggplot2 )之后,我試圖使用scale_fill_manual在ggplot中更改點和線的圖例和顏色,但是它似乎沒有工作 - geom_points保持黑色,並且geom_smooths保持藍色。 這是可重現的代碼:

type <- c("0", "0", "1", "2", "2", "2", "2", "1")
votes <- c(21, 28, 52, 66, 65, 42, 48, 39)
time <- c(1, 2, 3, 4, 5, 6, 7, 8)
df <- data.frame(type, votes, time)

test.plot <- ggplot(df, aes(y = votes, x = time, fill = type)) +
geom_point() +
geom_smooth(lwd = 0.75, lty = "dashed", se = FALSE, method = lm) +
scale_fill_manual(values=c("blue4", "purple4", "red4"),
                breaks=c("2","1","0"),
                labels=c("Standard", "Nonstandard", "Oddball"),
                name="Type")
test.plot

我試圖將標有“標准”的點和線顯示為深藍色,“非標准”點和線顯示深紫色,“Oddball”點和線顯示深紅色,但所有點都顯示黑色和線條都顯示藍色:

https://i.stack.imgur.com/IylCg.jpg

任何人都有修復? 先感謝您!

通常,我建議在繪圖之前重新映射變量,因為它使代碼更容易(並且意味着您可以先檢查數據中的值):

df$type <- factor(df$type, levels = 0:2,
                  labels = c("Oddball", "Nonstandard", "Standard"))

test.plot <- ggplot(df, aes(y = votes, x = time, colour = type)) +
  geom_point() +
  geom_smooth(lwd = 0.75, lty = "dashed", se = FALSE, method = lm) +
  scale_colour_manual(values=c("Standard" = "blue4", "Nonstandard" = "purple4",
    "Oddball" = "red4"), name="Type")

但是,否則,您只需將美學更改為colour而不是fill

test.plot <- ggplot(df, aes(y = votes, x = time, colour = type)) +
  geom_point() +
  geom_smooth(lwd = 0.75, lty = "dashed", se = FALSE, method = lm) +
  scale_colour_manual(values=c("blue4", "purple4", "red4"),
                    breaks=c("2","1","0"),
                    labels=c("Standard", "Nonstandard", "Oddball"),
                    name="Type")

情節

注意線和點使用colour而不是fill ,您只需要一個scale_x_manual的命名向量參數。

如果您的級別不是name的語法,則需要用雙引號括起來(例如"Non-standard" )。

另請參見手冊

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM