Ranji Raj
Ranji Raj

Reputation: 818

Generating LaTeX style scatter plot diagram using R ggplot2

I would like to generate a Latex diagram (a scatter plot) using ggplot2 in R.

Original image:

original

Code:

df <- data.frame(x = c(1,1.5,1.5,2,2,2,2,2,2,2.5,3,3,3,3,3.5,4,4.5,5,5,5.5,5.5,5.5,6,6,7)
                 ,y = c(1,1.5,2,2,2,2,2,2,2,2,2.5,2.5,3,3,3,3,3.5,3.5,3.5,3.5,3.5,4,4,4,4.5))
ggplot(df,aes(x=x,y=y)) + geom_point(alpha = 0.3)

What I obtain:

my plot

Upvotes: 2

Views: 352

Answers (2)

Peter
Peter

Reputation: 12739

You could try this which very nearly gets you all the way there:

  • Times New Roman type face
  • italicised axis titles
  • ragged grid
  • aspect ratio = 1

Shortfalls:

  • the "stealth" arrow head
  • axis tick marks above as well as below axis lines
df <- data.frame(x = c(1,1.5,1.5,2,2,2,2,2,2,2.5,3,3,3,3,3.5,4,4.5,5,5,5.5,5.5,5.5,6,6,7)
                 ,y = c(1,1.5,2,2,2,2,2,2,2,2,2.5,2.5,3,3,3,3,3.5,3.5,3.5,3.5,3.5,4,4,4,4.5))

library(ggplot2)
library(extrafont)

# helper dataframe for axis
df_arrow <- data.frame(x = c(0, 0),
                       y = c(0, 0),
                       xend = c(0, 8),
                       yend = c(8, 0)) 


ggplot(df,aes(x, y)) + 
  geom_point(colour = "blue", size = 5)+
  scale_x_continuous(breaks = 1:7, expand = expansion(add = c(0, 1)))+
  scale_y_continuous(breaks = 1:7, expand = expansion(add = c(0, 1)))+
  coord_fixed(xlim = c(0, 7), ylim = c(0, 7), clip = "off")+
  geom_segment(data = df_arrow, aes(x = x, xend = xend, y = y, yend = yend), size = 0.75, colour = "black",
             arrow = arrow(angle = 20, length = unit(3, "mm"), ends = "last", type = "closed"), linejoin = "mitre") +
  annotate("text", x = c(7.8, 0.3), y = c(0.3, 7.8), label = c("italic(x)", "italic(y)"), parse = TRUE, size = 6,  family = "Times New Roman")+
  labs(x = NULL,
       y = NULL)+
  theme_bw()+
  theme(panel.grid.major = element_line(colour = "gray80"),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        axis.ticks.length = unit(1, "mm"),
        text = element_text(size = 18,  family = "Times New Roman"))

Created on 2021-05-22 by the reprex package (v2.0.0)

Upvotes: 1

bird
bird

Reputation: 3326

One workaround would be:

ggplot(df,aes(x=x,y=y)) + geom_point(col = "blue", size = 5) +
        theme_minimal() +
        labs(x="", y="") +
        annotate(geom = "text", x = 1, y = 5, label = "y") +
        annotate("text", x = 7, y = 1, label = "x") +
        theme(axis.line.y = element_line(arrow = grid::arrow(length = unit(0.4, "cm"))),
              axis.line.x = element_line(arrow = grid::arrow(length = unit(0.4, "cm"))))

enter image description here

Upvotes: 3

Related Questions