在R中使用ggplot2的不同点形状

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

我想把我的点显示为形状1(中心点)和形状2(所有其他点),然后再添加这两个形状的图例。

我的代码如下

dd <- read.table(text="
dates   NB
15.05.2018  41
8.06.2018   81
20.06.2018  51
02.07.2018 0
14.07.2018  -1
7.08.2018   49
19.08.2018  112
12.09.2018  32
17.12.2018  -4", header=T, stringsAsFactors=FALSE)
dd$dates <- as.Date(dd$dates, "%d.%m.%Y")

library(ggplot2)
center <- subset(dd, dates=="2018-07-02")
ggplot(dd, aes(dates, NB, xend = center$dates, yend = center$NB)) +
  geom_segment(color="black") +
  geom_point(shape=1, fill="blue", color="black", size=2) +
  ylim(-100,150) +
  ylab("Normal Baseline [m]") +
  xlab("") +
  theme_linedraw() +  
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  theme(
    panel.grid.major.x = element_blank(),
    panel.grid.minor.x = element_blank(),
  ) +
  scale_x_date(breaks = dd$dates)

这是我期望达到的效果。

enter image description here

我该怎么做?谢谢你。

ggplot2 point
1个回答
1
投票

我想通过在你的data.frame中添加一列来解决这个问题,这样你就可以在ggplot调用中使用它作为美工。像这样的。

library(ggplot2)

dd <- read.table(text="
dates   NB
15.05.2018  41
8.06.2018   81
20.06.2018  51
02.07.2018 0
14.07.2018  -1
7.08.2018   49
19.08.2018  112
12.09.2018  32
17.12.2018  -4", header=T, stringsAsFactors=FALSE)
dd$dates <- as.Date(dd$dates, "%d.%m.%Y")

#Add point as a column to dd so you can add it as an aesthetic
dd$point <- ifelse(dd$dates == "2018-07-02", "Center Point", "Other Points")

ggplot(dd, aes(dates, NB, colour = point, shape = point)) +
  geom_segment(aes(xend = dd[point == "Center Point","dates"],
                   yend = dd[point == "Center Point","NB"]),
               colour = "black") +
  geom_point() +
  ylim(-100,150) +
  ylab("Normal Baseline [m]") +
  xlab("") +
  scale_colour_manual("", values = c("Center Point" = "red", "Other Points" = "black")) +
  scale_shape_manual("", values = c("Center Point" = 1, "Other Points" = 2)) +
  theme_linedraw() +  
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  theme(
    panel.grid.major.x = element_blank(),
    panel.grid.minor.x = element_blank(),
    legend.position = c(.8, .8)) +
  scale_x_date(breaks = dd$dates)

创建于2020-05-04 重读包 (v0.3.0)

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