EngBIRD
EngBIRD

Reputation: 2025

Plot features cropped by Margin

When I compile the following MWE I observe that the maximum point (3,5) is significantly cut/cropped by the margins.

The following example is drastically reduced for simplicity.

In my actual data the following are all impacted by limiting my coord_cartesian manually if the coresponding x-axis aesthetic is on the max x value.

MWE

library(ggplot2)
library("grid")

print("Program started")

n = c(0.1,2, 3, 5) 
s = c(0,1, 2, 3)  
df = data.frame(n, s)

gg <- ggplot(df, aes(x=s, y=n))
gg <- gg + geom_point(position=position_dodge(width=NULL), size = 1.5) 
gg <- gg + geom_line(position=position_dodge(width=NULL))

gg <- gg + coord_cartesian( ylim = c(0, 5), xlim = c((-0.05)*3, 3));

print(gg)

print("Program complete - a graph should be visible.")

To show my data appropriately I would consider using any of the following that are possible (influenced by the observation that the x-axis labels themselves are never cut):

  1. Make the margin transparent so the point isn't cut
    • unless the point is cut by the plot area and not the margin
  2. Bring the panel with the plot area to the front
    • unless the point is cut by the plot area and not the margin so order is independent
  3. Use xlim = c((-0.05)*3, (3*0.05)) to extend the axis range but implement some hack to not show the overhanging axis bar after the maximum point of 3?
    • this is how I had it originally but I was told to remove the overhang after the 3 as it was unacceptable.

Upvotes: 1

Views: 194

Answers (1)

eipi10
eipi10

Reputation: 93811

Is this what you mean by option 1:

gg <- ggplot(df, aes(x=s, y=n)) +
  geom_point(position=position_dodge(width=NULL), size = 3) +
  geom_line(position=position_dodge(width=NULL)) + 
  coord_cartesian(xlim=c(0,3), ylim=c(0,5))

# Turn of clipping, so that point at (3,5) is not clipped by the panel grob
gg1 <- ggplot_gtable(ggplot_build(gg))
gg1$layout$clip[gg1$layout$name=="panel"] <- "off"
grid.draw(gg1)

enter image description here

Upvotes: 1

Related Questions