如何在ggplot2中使用geom_line、geom_point指定颜色并进行注释?

问题描述 投票:0回答:1

我正在尝试修改Jeff Lewis (2023-10-23)国会极化,并且我无法控制geom_line和geom_point中的颜色。

以下似乎是我用他的 12 个子集得到的最接近我想要的结果 2774点:

library(ggplot2)
PolarDatSmpl <- data.frame(
  year=rep(c(1879, 1951, 2023), 4), 
  chamber=rep(c('House', 'Senate'), e=3, len=12), 
  party=rep(c('DEM', 'REP'), e=6), 
  value=c(-.39, -.26, -.38, -.45, -.20, -.35, 
           .40,  .28,  .51,  .30,  .28,  .55) )

PolarDatSmpl$pc <- with(PolarDatSmpl, 
    interaction(party, chamber))
  
# I want lines and points labeled with colors 
# and text 

PolarColors <- data.frame(
  chamber=rep(c('House', 'Senate'), e=2), 
  party=rep(c('DEM', 'REP'), 2), 
  Color=c('blue', 'red', 'darkblue', 'darkred'), 
  yearTxt=c(1960.3, 1944.3, 1961, 1945),  
  yearPch=c(1944.3, 1927.8, 1944, 1928), 
  value=c(-.4, .5, -.33, .4) )

#value=c(-.5, .4, -.43, .35) )
#c(.5, .4, -.43, -.35) 
PolarColors$pc <- with(PolarColors, 
    interaction(party, chamber))
rownames(PolorColors) <- PolarColors$pc

PolarDatSmpl$Color <- PolarColors[
  PolarDatSmpl$pc, 'Color']

p1 <- ggplot(data=PolarDatSmpl, 
    aes(x=year, y=value, group=pc, color=Color)) +
  theme_bw() + 
  theme(legend.position='none') + 
  geom_line() + geom_point(mapping=aes(
    shape=factor(chamber) )) 

# What do I need to do to get the desired colors? 

p2 <- p1 + with(PolarColors, annotate('text', 
    x=yearTxt, y=value, label=pc, color=Color)) + 
  geom_point(PolarColors, mapping = aes( 
    x=yearPch, y=value, shape=factor(chamber) ))
p2

这给了我想要的一切,除了点和线的颜色。我可以使用

annotate
指定颜色,并使用
geom_plot
的配套校准来将图例放在我想要的位置,但我无法控制线条颜色。 (我曾经对点和线进行了着色,但是当我添加注释时,它们就被破坏了。)

建议?谢谢,斯宾塞·格雷夫斯

ggplot2 colors line point
1个回答
0
投票

要使用 df 列中的 R 颜色名称/十六进制值,请使用

scale_color_identity()
。请注意,
scale_color_identity()
的默认行为不会创建图例,因此如果您没有
shape
的美感,则不需要
theme(legend.position = "none")
:

ggplot(data = PolarDatSmpl,
       aes(x = year, y = value, group = pc, colour = Color)) +
  geom_line() +
  geom_point(aes(shape = factor(chamber))) +
  with(PolarColors,
       annotate('text', x = yearTxt, y = value, label = pc, color = Color)) + 
  geom_point(PolarColors,
             mapping = aes(x = yearPch, y = value, shape = factor(chamber))) +
  scale_color_identity() +
  theme_bw() +  
  theme(legend.position = "none")

1

© www.soinside.com 2019 - 2024. All rights reserved.