How to remove blank from geom_line in ggplot2? - r

geom_line has big gap in line two sides, how to remove this gap!
R scripts is listed as follow,
p <- ggplot(singJanS)+ geom_line(aes(x=sn,y=diff))
p <- p + geom_hline(yintercept=seq(-0.8,0.8,by=0.4), linetype=2, colour="grey") +
geom_vline(xintercept=seq(15,744,by=24), linetype=6, colour="red") +
geom_vline(xintercept=seq(23,744,by=24), linetype=6, colour="blue") +
ylab(Delta~T~' ('~degree~C~')')+xlab("")+
scale_x_continuous(breaks = c(0,120,240,360,480,600,720))+
scale_y_continuous(breaks = c(-0.8,-0.4,0,0.4,0.8)) +theme_bw()

The solution suggested by #Z.Lin works correctly.
The two gaps are removed if you add expand = c(0, 0) to scale_x_continuous().
set.seed(1)
singJanS <- data.frame(sn=1:740, diff=rnorm(740)/3)
p <- ggplot(singJanS)+ geom_line(aes(x=sn,y=diff))
p <- p + geom_hline(yintercept=seq(-0.8,0.8,by=0.4), linetype=2, colour="grey") +
geom_vline(xintercept=seq(15,744,by=24), linetype=6, colour="red") +
geom_vline(xintercept=seq(23,744,by=24), linetype=6, colour="blue") +
ylab(Delta~T~' ('~degree~C~')')+xlab("")+
scale_x_continuous(breaks = c(0,120,240,360,480,600,720),expand = c(0, 0))+
scale_y_continuous(breaks = c(-0.8,-0.4,0,0.4,0.8)) +theme_bw()
p

Try adding to your code
+ scale_x_continuous(limits = c(0, 750))

Related

How can I add a legend to my ggplot? Im using geom_line and geom_ribbon

Good afternoon,
I use the following code to generate a plot:
ggplot() +
geom_line(data = disDataHeadItems, aes(x=disDataHeadItems$x,
y=disDataHeadItems$Freq)) +
geom_line(data = disDataLongTail, aes(x=disDataLongTail$x,
y=disDataLongTail$Freq)) +
xlab("Item id") +
ylab("# of occurrences") +
scale_x_continuous(breaks=seq(5, 75, 10), expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
geom_ribbon(aes(ymin=0, ymax=disDataHeadItems$Freq,
x=disDataHeadItems$x), fill="#CC6666") +
geom_ribbon(aes(ymin=0, ymax=disDataLongTail$Freq,
x=disDataLongTail$x), fill="#66CC99") +
geom_vline(xintercept=19, linetype="dotted")
This creates the following plot, which im very happy with :)
Now I want to add a legend which just indicated that the red part is the top-head items and the green part is the long tail of the data. When I look it up I only find answers that indicate how to alter the legend. But mine just does not show up. Any help is welcome :)
Putting the comments together and adding some random dataframe results in this:
library(ggplot2)
disDataHeadItems <- data.frame(
x = runif(100,1,100),
Freq = runif(100,5,10)
)
disDataLongTail <- data.frame(
x = runif(100,1,100),
Freq = runif(100,5,10)
)
ggplot() +
geom_line(data = disDataHeadItems, aes(x=x,
y=Freq)) +
geom_line(data = disDataLongTail, aes(x=x,
y=Freq)) +
xlab("Item id") +
ylab("# of occurrences") +
scale_x_continuous(breaks=seq(5, 75, 10), expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
geom_ribbon(aes(ymin=0, ymax=disDataHeadItems$Freq,
x=disDataHeadItems$x, fill="#CC6666")) +
geom_ribbon(aes(ymin=0, ymax=disDataLongTail$Freq,
x=disDataLongTail$x, fill="#66CC99")) +
geom_vline(xintercept=19, linetype="dotted")

How to plot a lign spanning these two graphs?

Consider the following figure:
mainplot = ggplot(mtcars, aes(y=mpg,x=wt)) + geom_point() + theme_classic(15) + ylim(c(5,40)) + geom_hline(yintercept=c(15,25), color="red")
gg = ggplot(data.frame(mpg=0), aes(x=mpg))
f = function(mpg,center) {exp(-(mpg - center)^2/(20))}
f15 = function(mpg) {f(mpg,15)}
f25 = function(mpg) {f(mpg,25)}
sideplot = gg + stat_function(fun = f15, linetype="dashed") + stat_function(fun = f25, linetype="dashed") + theme_classic(15) + scale_x_continuous(name=NULL,limits=c(5,40)) + coord_flip() + ylab("f") + theme(axis.title.y=element_blank(),axis.text.y=element_blank(),axis.ticks.y=element_blank()) + geom_vline(xintercept=c(15,25), color="red")
multiplot(mainplot, sideplot, layout=matrix(c(1,1,1,2),nrow=1))
As the figure is made of two independent graphs, the red horizontal lines are interrupted. Is there any way I can make it a continuous line?
It is possible that the easiest solution consists at using Adobe Illustrator (or some equivalent) to modify the figure.
Not really a solution but a work around.
Reduce the margins to stick the two graphs together
Make your line a dashed line
Remove the y axis line of the sideplot
mainplot = ggplot(mtcars, aes(y=mpg,x=wt)) + geom_point() + theme_classic(15) + ylim(c(5,40)) + geom_hline(yintercept=c(15,25), color="red", linetype="dashed") + theme(plot.margin = unit(c(1,0,1,1), "cm"))
sideplot = gg + stat_function(fun = f15, linetype="dashed") + stat_function(fun = f25, linetype="dashed") + theme_classic(15) + scale_x_continuous(name=NULL,limits=c(5,40)) + coord_flip() + ylab("f") + theme(axis.line.y=element_blank(),axis.title.y=element_blank(),axis.text.y=element_blank(),axis.ticks.y=element_blank()) + geom_vline(xintercept=c(15,25), color="red", linetype="dashed") + theme(plot.margin = unit(c(1,1,1,0), "cm"))
multiplot(mainplot, sideplot, layout=matrix(c(1,1,1,2),nrow=1))

Shift text in ggplot up

Using the this code gives the plot printed below. As you can see the percentages are printed on the border of the bars. I would like to have them above the bars. Is there a way to achieve this?
p <- ggplot(data=iris, aes(x=factor(Species), fill=factor(Species)))
p + geom_bar() + scale_fill_discrete(name="Species") + labs(x="") +geom_text(aes(y = (..count..),label = scales::percent((..count..)/sum(..count..))), stat="bin",colour="darkgreen") + theme(legend.position="none")
Just add an arbitrary value to y.
p <- ggplot(data=iris, aes(x=factor(Species), fill=factor(Species)))
p + geom_bar() + scale_fill_discrete(name="Species") + labs(x="") +geom_text(aes(y = (..count..) + 10,label = scales::percent((..count..)/sum(..count..))), stat="bin",colour="darkgreen") + theme(legend.position="none")
Or, as per Heroka's comment, use vjust, which is a better solution
p <- ggplot(data=iris, aes(x=factor(Species), fill=factor(Species)))
p + geom_bar() + scale_fill_discrete(name="Species") + labs(x="") +
geom_text(aes(y = (..count..),
label = scales::percent((..count..)/sum(..count..))),
stat="bin",
colour="darkgreen", vjust = -0.5) +
theme(legend.position="none")
But as this makes things quite cramped at the top you might want to add + expand_limits(y = c(0, 60)) to give you a bit more space for the labels.

Draw lines between two facets in ggplot2

How can I draw several lines between two facets?
I attempted this by plotting points at the min value of the top graph but they are not between the two facets. See picture below.
This is my code so far:
t <- seq(1:1000)
y1 <- rexp(1000)
y2 <- cumsum(y1)
z <- rep(NA, length(t))
z[100:200] <- 1
df <- data.frame(t=t, values=c(y2,y1), type=rep(c("Bytes","Changes"), each=1000))
points <- data.frame(x=c(10:200,300:350), y=min(y2), type=rep("Bytes",242))
vline.data <- data.frame(type = c("Bytes","Bytes","Changes","Changes"), vl=c(1,5,20,5))
g <- ggplot(data=df, aes(x=t, y=values)) +
geom_line(colour=I("black")) +
facet_grid(type ~ ., scales="free") +
scale_y_continuous(trans="log10") +
ylab("Log values") +
theme(axis.text.x = element_text(angle = 90, hjust = 1), panel.margin = unit(0, "lines"))+
geom_point(data=points, aes(x = x, y = y), colour="green")
g
In order to achieve that, you have to set the margins inside the plot to zero. You can do that with expand=c(0,0). The changes I made to your code:
When you use scale_y_continuous, you can define the axis label inside that part and you don't need a seperarate ylab.
Changed colour=I("black") to colour="black" inside geom_line.
Added expand=c(0,0) to scale_x_continuous and scale_y_continuous.
The complete code:
ggplot(data=df, aes(x=t, y=values)) +
geom_line(colour="black") +
geom_point(data=points, aes(x = x, y = y), colour="green") +
facet_grid(type ~ ., scales="free") +
scale_x_continuous("t", expand=c(0,0)) +
scale_y_continuous("Log values", trans="log10", expand=c(0,0)) +
theme(axis.text.x=element_text(angle=90, vjust=0.5), panel.margin=unit(0, "lines"))
which gives:
Adding lines can also be done with geom_segment. Normally the lines (segments) will appear in both facets. If you want them to appear between the two facets, you will have to restrict that in data parameter:
ggplot(data=df, aes(x=t, y=values)) +
geom_line(colour="black") +
geom_segment(data=df[df$type=="Bytes",], aes(x=10, y=0, xend=200, yend=0), colour="green", size=2) +
geom_segment(data=df[df$type=="Bytes",], aes(x=300, y=0, xend=350, yend=0), colour="green", size=1) +
facet_grid(type ~ ., scales="free") +
scale_x_continuous("t", expand=c(0,0)) +
scale_y_continuous("Log values", trans="log10", expand=c(0,0)) +
theme(axis.text.x=element_text(angle=90, vjust=0.5), panel.margin=unit(0, "lines"))
which gives:

Changing Y-axis breaks in ggplot2

I have this code to give the graph shown below:
d=ggplot(df, aes(x=Year, y=NAO_Index, width=.8)) +
+ geom_bar(stat="identity", aes(fill=NAO_Index>0), position='identity', col = 'transparent') +
+ theme_bw() + scale_fill_manual(values=c("royalblue", "firebrick3"), name="NAO Oscillation", labels=c("Negative", "Positive"), guide=guide_legend(reverse=TRUE)) +
theme(legend.position=c(0.06, 0.92)) +
+ theme(axis.title.x=element_text(vjust=-0.2)) +
+ geom_line(data=dfmoveav, aes(x=Year ,y=moveav)) +
+ ylab("NAO Index") +
+ ggtitle("NAO Index between 1860 and 2050") +
+ scale_x_continuous(breaks=c(seq(1860,2050,10))) +
+ scale_y_continuous(breaks=c(seq(-3.5,3.5,0.5)))
I am only really concerned with the last line. In the graph the y-axis only goes from -3 to 2.5. How do I get it from -3.5 to 3.5 so it is even?
I'm sure I am making a simple error but cannot figure it out!
Many thanks in advance.
You are almost there. Try to set limits.
d=ggplot(df, aes(x=Year, y=NAO_Index, width=.8)) +
+ geom_bar(stat="identity", aes(fill=NAO_Index>0), position='identity', col = 'transparent') +
+ theme_bw() + scale_fill_manual(values=c("royalblue", "firebrick3"), name="NAO Oscillation", labels=c("Negative", "Positive"), guide=guide_legend(reverse=TRUE)) +
theme(legend.position=c(0.06, 0.92)) +
+ theme(axis.title.x=element_text(vjust=-0.2)) +
+ geom_line(data=dfmoveav, aes(x=Year ,y=moveav)) +
+ ylab("NAO Index") +
+ ggtitle("NAO Index between 1860 and 2050") +
+ scale_x_continuous(breaks=c(seq(1860,2050,10))) +
+ scale_y_continuous(breaks=c(seq(-3.5,3.5,0.5)), limits = c(-3.5, 3.5))
More about it here
To map line into the legend you should map the variable to aesthetic. But it's not trivial and you'll find references to avoid this approach.
df <- data.frame(year=factor(seq(1:10)),
nao = rnorm(10, 0, 2),
mov = rnorm(10, 0,3))
df2 <- data.frame(year=factor(seq(1:10)),
mov = df$nao+rnorm(10, 0, 0.1),
g = .1)
ggplot() +
geom_bar(data = df, aes(x=year, y=nao, fill=nao > 0), width=.8,
stat="identity", position ='identity', col = 'transparent') +
geom_line(data = df2, aes(x = year, y = mov, group = g, size = g)) +
scale_fill_manual(values=c("royalblue", "firebrick3"),
name="NAO Oscillation",
labels=c("Negative", "Positive"),
guide=guide_legend(reverse=TRUE)) +
scale_size('Trend', range = 1, labels = 'Moving\naverage') +
ggtitle("NAO Index between 1860 and 2050") +
scale_y_continuous(breaks=c(seq(-5,5,0.5)), limits = c(-5, 5)) +
ylab("NAO Index") +
theme(legend.position = c(0.07, 0.80),
axis.title.x = element_text(vjust= -0.2),
legend.background = element_blank())
This may not be the best approach to map variables to aesthetics.

Resources