Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plot this in ggplot. Controlling y axis line within a range

Tags:

plot

r

ggplot2

axis

This is using base, where I can control the x and y axis range, where exactly the line should be drawn.

plot(mtcars$mpg, mtcars$hp, ylim = c(0, 400), xlim = c(0, 50), axes = F, xlab  = 'mpg', ylab = 'hp', pch = 16)
axis(side = 2, at = seq(100, 400, 100))
axis(side = 1, at = seq(10, 30, 10))

enter image description here

ggplot(data = mtcars, aes(x = mpg, y = hp))+geom_point()+
theme(panel.background = element_blank())+
scale_x_continuous(breaks = seq(10, 30, 10), limits = c(0, 50))+
scale_y_continuous(breaks = seq(100, 400, 100), limits = c(0, 400))

enter image description here

How do I add axis line exactly like base plot ? I have tried scale_y_continuous and scale_x_continuous but it always draws till the end of the plot.

like image 975
PoisonAlien Avatar asked Mar 01 '17 08:03

PoisonAlien


People also ask

How do I change the Y axis range in R?

To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.

How do I change the y axis values in ggplot2?

Use scale_xx() functions It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.


1 Answers

You can get there using the ggthemes package:

library(ggthemes)
ggplot(data = mtcars, aes(x = mpg, y = hp)) + 
  geom_point() +
  geom_rangeframe(data = data.frame(mpg = c(10, 30), hp = c(100, 400))) +
  theme_tufte() +
  scale_x_continuous(breaks = seq(10, 30, 10), limits = c(0, 50))+
  scale_y_continuous(breaks = seq(100, 400, 100), limits = c(0, 400))

enter image description here

You can also draw them manually, if you want:

ggplot(data = mtcars, aes(x = mpg, y = hp)) + 
  geom_point() +
  geom_segment(
    aes_all(c('x', 'y', 'xend', 'yend')),
    data.frame(x = c(0, 10), xend = c(0, 30), y = c(100, 0), yend = c(400, 0))
  ) +
  theme(panel.background = element_blank()) +
  scale_x_continuous(breaks = seq(10, 30, 10), limits = c(0, 50), expand = c(0, 0))+
  scale_y_continuous(breaks = seq(100, 400, 100), limits = c(0, 400), expand = c(0, 0))

enter image description here

like image 177
Axeman Avatar answered Oct 21 '22 20:10

Axeman