Search code examples
ggplot2point

Different point shapes with ggplot2 in R


I want to show my points as shape 1 (center point) and shape 2 (all other points) and after than add a legend of these two shapes.

My codes are below

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)

This is the result i expect to achieve:

enter image description here

How can I do? Thank you.


Solution

  • I would think about this by adding a column to your data.frame so you can use it as an aesthetic in the ggplot call. Something like this:

    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)
    

    Created on 2020-05-04 by the reprex package (v0.3.0)