user2659088
user2659088

Reputation: 133

how to make the value on Y axis start from zero in R, ggplot2

currently, I'm using ggplot2 to make density plot.

ggplot(data=resultFile,aes(x=V19, colour=V1) ) +
geom_line(stat="density") +
xlab("score") +
ylab("density") +
ggtitle(paste(data_name,protocol,level,sep=" ")) +
theme(legend.title=element_blank(), legend.position=c(0.92,0.9)) +
scale_color_manual(values=c("blue","red"),
                   labels=c("A", "B"))

using this code, I can get the plot below. enter image description here

However, I can get different plot if I used plot(density()...) function in R. enter image description here

Y value starts from 0.

How can I make the ggplot's plot as like plot(density()...) in R?

Upvotes: 4

Views: 5259

Answers (2)

amatsuo_net
amatsuo_net

Reputation: 2448

ggplot obviously cut off the x-axis at the min and max of the empirical distribution. You can extend the x-axis by adding xlim to the plot but please make sure that the plot does not exceed the theoretical limit of the distribution (in the example below, the theoretical limit is [0, 1], so there is not much reason to show outside the range).

set.seed(1)
temp <- data.frame(x =runif(100)^3)
library(ggplot2)
ggplot(temp, aes(x = x)) + geom_line(stat = "density" + xlim(-.2, 1.2)
plot(density(temp$x))

Upvotes: 0

Sorif Hossain
Sorif Hossain

Reputation: 1351

    ggplot(data=resultFile,aes(x=V19, colour=V1) ) +
    ylim(0,range) #you can use this . 
    geom_line(stat="density") +
    xlab("score") +
   ylab("density") +
   ggtitle(paste(data_name,protocol,level,sep=" ")) +
   theme(legend.title=element_blank(), legend.position=c(0.92,0.9)) +
   scale_color_manual(values=c("blue","red"),
   labels=c("A", "B"))

Upvotes: 1

Related Questions