簡體   English   中英

如何在同一組中為點和文本應用不同的顏色?

[英]How to apply different colors for point and text but in the same group?

我正在嘗試繪制一個圖,其中點的顏色為 3 組的紅色、綠色、藍色,相關標簽的顏色為深紅色、深綠色、深藍色。

我嘗試了以下代碼,但沒有使用深色。

library(ggplot2)
ggplot(data.frame("Year" = 2013:2022, 
                  "Value" = round(rnorm(10), 1), 
                  "Group" = sample(letters[1:3], 10, T)),
       aes(Year, Value)) + 
  geom_point(aes(color = Group)) +
  geom_text(aes(label = Value, color = Group), vjust = -1, show.legend = FALSE) +
  scale_color_manual(values = c("red", "green", "blue", "darkred", "darkgreen", "darkblue"))

我發現ggnewscale包似乎可以滿足您的需求。 https://ggplot2.tidyverse.org/articles/faq-customising.html#colours

library(ggplot2)
library(ggnewscale)
#> Warning: package 'ggnewscale' was built under R version 4.1.3
ggplot(data.frame("Year" = 2013:2022, 
                  "Value" = round(rnorm(10), 1), 
                  "Group" = sample(letters[1:3], 10, T)),
       aes(Year, Value)) + 
  geom_point(aes(color = Group)) +
  scale_color_manual(values = c("red", "green", "blue")) +
  new_scale_color() + 
  geom_text(aes(label = Value, color = Group), vjust = -1, show.legend = FALSE) +
  scale_color_manual(values = c("darkred", "darkgreen", "darkblue"))

reprex 包於 2022-06-29 創建 (v2.0.1)

我們可以對點使用fill而不是顏色,並將形狀設置為 21。如果您不希望點周圍有邊框,請將stroke = NA添加到geom_point

library(ggplot2)
ggplot(data.frame("Year" = 2013:2022, 
                  "Value" = round(rnorm(10), 1), 
                  "Group" = sample(letters[1:3], 10, T)),
       aes(Year, Value)) + 
  geom_point(aes(fill = Group), pch=21) +
  geom_text(aes(label = Value, color = Group), vjust = -1, 
            show.legend = FALSE) +
  scale_color_manual(values = c("darkred", "darkgreen", "darkblue")) +
  scale_fill_manual(values = c("red", "green", "blue"))

暫無
暫無

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

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