Keeping tick marks attached to my axis in R ggplot2 when zooming - r

I would like to export this graph from RStudio on a larger resolution but when I do this the tick marks of the x-axis separate from the axis.
I have looked at documentation for theme() but did not find a relevant function: http://docs.ggplot2.org/0.9.3/theme.html
So how can I keep my ticks connected to the x-axis?
I tried using the space between ticks and axis labels but it just changes the relevant spacing, but does not change the spacing I am talking about.
Code to generate the images I depicted below:
require(data.table)
require(ggplot2)
require(grid)
setsTimeline <- data.table(Set=c("Training Set","Validation Set","Test Set","Training Set","Validation Set","Test Set","Training Set","Validation Set","Test Set","Training Set","Validation Set","Test Set","Training Set"),
StartDate=c(1380708900,1402963200,1420070400,1421280000,1410912000,1396310400,1397520000,1418860800,1404172800,1405382400,1395100800,1412121600,1413331200),
EndDate= c(1395099900,1404171900,1421279100,1430985600,1412120700,1397519100,1402962300,1420069500,1405381500,1410911100,1396309500,1413330300,1418859900))
setsTimeline[,StartLabel:=as.POSIXct(StartDate,tz="UTC",origin="1970-01-01")]
setkey(setsTimeline,StartDate)
breaks <- c(1380708900,1395100800,1402963200,1410912000,1418860800,1430985600)
labels <- as.POSIXct(breaks,tz="UTC",origin="1970-01-01")
ggplot(setsTimeline, aes(colour=Set)) +
geom_segment(aes(x=StartDate, xend=EndDate, y="group", yend="group"), size=10) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
aspect.ratio=5e-02,
axis.text.x = element_text(colour='black', angle = 45, size = 16, hjust = 1, vjust = 1),
axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
legend.text = element_text(colour='black', size = 16),
legend.title = element_text(colour='black', size = 0),
legend.position = 'top',
plot.title = element_text(colour='black', size = 18),
plot.margin = unit(c(0,1,0,3.5), "cm")) +
xlab(NULL) +
ylab(NULL) +
ggtitle(NULL) +
coord_cartesian(xlim = c(1380708900,1430985600), ylim = NULL) +
scale_x_continuous(breaks=breaks,labels=labels)
Small res:
High res:

Related

R ggplot color bin widths appear unequal

Hello I am ploting a graph which will have the legend,width of legend items not same can any one help me to resolve my problem
data file
< https://drive.google.com/file/d/1EKhRwup3vUC3KVFOOh4XtKERIr8FQj3x/view?usp=sharing>
code I have used
df=read.table("test.txt",sep='\t', header=TRUE)
df = data.frame(df)
nCol <- 15
myCol <- viridis(n = nCol)
myCol
ggplot(df, aes(log(data1), log(data2),color=data3),cex=1.9)+
geom_point() +
scale_colour_stepsn(colours = c(myCol),breaks = seq(0,100,by=10))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))+
theme(text = element_text(size = 12, face="bold"),
legend.text = element_text(size = 7, face="bold"), legend.position="top",
legend.key.size = unit(10, "mm"),
legend.key.width=unit(10, "mm"))
at the end of legend 90-100 width is high compare to others
There are a couple of asides before addressing your main concern:
You can simplify your code by using scale_color_binned(type = "viridis"), which gives the same result as creating a vector of
viridis colors and interpolating them as you are doing, with the added advantage that you don't need to load the viridis library.
You can use log scales on the x and y axis without having to transform your
data, by using scale_x_log10() and scale_y_log10()
You can simplify your theme call by first calling theme_classic(), which gets rid of the need to specify all those element_blank() components.
For the specific problem that you encountered though, the reason for the appearance is that breaks are for the "internal" breaks of the binned scale. The outer edges of your scale are not breaks, but limits. By default, limits are not shown on binned scales, but you can turn them on using show.limits = TRUE after setting the limits to the desired value of c(0, 100)
So your above code can be rewritten as:
df <- read.table("test.txt", sep = "\t", header = TRUE)
ggplot(df, aes(log(data1), log(data2), color = data3), cex = 1.9) +
geom_point() +
scale_colour_binned(type = "viridis",
breaks = 1:9 * 10,
limits = c(0, 100),
show.limits = TRUE,
labels = function(x) round(x)) +
theme_classic() +
theme(text = element_text(size = 12, face = "bold"),
legend.text = element_text(size = 7, face = "bold"),
legend.position = "top",
legend.key.size = unit(10, "mm"))

Set y limits in Bar Chart ggplot2

I have created a bar chart which shows the sales of products in a particular category. This is the bar chart. As you can see it is not very clear so I am trying to set limits for the Y axis.
I create the bar chart with the following line:
bakerySales <- ggplot(sales_bakery, aes(ProductName, ProductSales))+
stat_summary(fun.y=sum,geom="bar",colour="red",fill="red",show.legend =
FALSE)
I then go on to apply a theme to the bar chart using:
bakerySales <- bakerySales +
theme(axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_text(colour = "black", size = 14, angle = 60,
hjust = 1),
axis.text.y = element_text(colour = "black", size = 14),
panel.background = element_rect(fill = "white"),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
axis.line = element_line(colour = "black", size = 1),
legend.position = "none",
plot.title = element_text(lineheight = 8, face = "bold"))
I have tried to set the limits for the y axis using:
bakerySales <- bakerySales + ylim(5000,10000)
When I do this I lose the content of the bar chart, It looks like this.
Can someone please tell me where I am going wrong.
Thanks
If you want to zoom in on specifix ylimits, you could use the coord_cartesian function. I do not have the bakerysales dataset, this is an example using mtcars data:
ggplot(mtcars, aes(x = gear, y = qsec)) +
stat_summary(fun.y=sum,geom="bar",colour="red",fill="red",show.legend = FALSE) +
coord_cartesian(ylim = c(200, 300))
Maybe you want
+ coord_cartesian(ylim = c(5000,10000))
df <- data.frame(x = c("a","b"), y = c(1000, 2000))
ggplot(df, aes(x=x,y=y)) +
geom_bar(stat="identity") +
coord_cartesian(ylim = c(500,3000))

Adjust the distance between x labels and the chart using ggplot2

I am trying to cut the distance between x axis labels and the graph, so that it would be more clearly visible which bar responds to what lable. This is the code and the graph:
graph196 <- ggplot(serazene196a, aes(x = okres2, y = (NEPO_ANO_NE.mean/100), ordered=TRUE)) +
geom_bar(stat = "Identity", colour="white")
graph196 + theme_stata() + theme(axis.text.x = element_text(angle = 90, hjust = 1, size = 10, vjust=0.5),
axis.text.y = element_text(angle = 0),
axis.title.x = element_blank(), axis.title.y = element_blank(),
axis.text.y = element_text(size = 10), axis.ticks.x = element_blank(),
axis.ticks.y = element_blank(),
panel.border = element_blank(),
plot.background = element_rect(fill = 'white')) +
scale_y_continuous(labels=percent)
It looks like that: [1]: http://i.stack.imgur.com/bBjdn.jpg
If I increase hjust to 1.2, the labels appear close enough to the graph, but at the same time they are not aligned, so the graph does not look good at all: [1]: http://i.stack.imgur.com/C7Boc.jpg.
Is there an option of how to align the labels with increased hjust or otherwise bring the entire labels closer to the graph?
The problem is similar to this one: Adjust distance between x-axis and text in R plot, except the fact that I am using ggplot2.
The problem is even though you've hidden tick marks they still occupy space. You can force the labels closer by adjusting the margins of your text labels.
element_text(angle = 90, hjust = 1, size = 10, vjust=0.5, margin=margin(-15,0,0,0)
The margins are defined as (top,right,bottom,left) and I've adjusted the top margin to be negative.

Grid appears in ggplot2 depending on axis option

I have created a map that shows that shows the intensity of a variable by making a grid of the entire United states. That works pretty well but the problem that a grid appears when I save the plot. The following simplified code reproduces my problem.
library(ggplot2)
library(scales)
library(gridExtra)
#Construct grid
n.dots <- 1000
x <- seq(0, 100, length.out = n.dots)
y <- seq(0, 100, length.out = n.dots)
grid <- expand.grid(x, y)
colnames(grid) <- c("x", "y")
grid$value <- grid$x*grid$y
#Make graph
mytheme <- theme(axis.text = element_blank(),
axis.title = element_blank(),
plot.margin=unit(c(0,0,0,0), "lines"),
axis.ticks = element_blank(),
plot.title = element_blank(),
panel.border = element_blank(),
panel.grid = element_blank(),
legend.title=element_blank(),
legend.key = element_rect(fill = "white", colour = "white"), text=element_text(size=10),
legend.position="none")
p <- ggplot() + geom_point(data=grid, aes(x=x, y=y, colour = value), size = 0.1) + scale_colour_gradient("value", low="green", high = "red") + theme_bw() + mytheme
ggsave(p, filename = "Map intensity.png", width = 4, height = 4, units = "in", dpi = 600)
The png file shows a grid which I do not want. By commenting out axis.text and axis.title in theme options I selected the problem disappears.
#Make graph
mytheme <- theme(#axis.text = element_blank(),
#axis.title = element_blank(),
plot.margin=unit(c(0,0,0,0), "lines"),
axis.ticks = element_blank(),
plot.title = element_blank(),
panel.border = element_blank(),
panel.grid = element_blank(),
legend.title=element_blank(),
legend.key = element_rect(fill = "white", colour = "white"), text=element_text(size=10),
legend.position="none")
p <- ggplot() + geom_point(data=grid, aes(x=x, y=y, colour = value), size = 0.1) + scale_colour_gradient("value", low="green", high = "red") + theme_bw() + mytheme
ggsave(p, filename = "Map intensity_2.png", width = 4, height = 4, units = "in", dpi = 600)
In that last png file the graph is all smooth as I want it and there is no grid. But it contains axis text and axis titles, which I do not want. What is causing this behavior?
One solution could be to increase the point size but I am hoping to keep the graph as precise as possible. I am interested in knowing why the axis options change the appearance of a grid in the file that is saved.
Thank you.

ggplot legend issues: elements overlapping and/or missing? [geom_pointrange, geom_point and geom_segment]

Using the following data frame and vector:
df<-data.frame(time=as.POSIXct(c("2013-04-23 10:00:00","2013-04-23 12:08:00")),
info=c("point","point"),
bin=c("bin length","bin length"),
upper=c(3.7,1.54),
lower=c(3.11,1.13),rate=c(3.43,1.33))
deltaTS=df$time[2]-df$time[1]
The data.frame can be graph using the following code:
ggplot(data=df,aes(x=time+deltaTS*.97,y=rate))+
geom_pointrange(aes(ymin=lower,ymax=upper,x=time+deltaTS*.97,position="identity"),color="white",show_guide=T)+
geom_point(size=7,color="white",aes(color=info,fill=info,group=info))+
geom_point(size=6,color="tomato",aes(color=info,fill=info,group=info))+
geom_segment(aes(x=time, y=0, xend=time+(deltaTS*.96), yend=0,fill=bin,group=bin), alpha=0.7,color="black",size=3,show_guide=F)+
geom_segment(aes(x=time+(deltaTS*.01), y=0, xend=time+(deltaTS*.95), yend=0,fill=bin,group=bin), alpha=0.7,color="tomato",size=2,show_guide=T)+
theme(legend.title = element_text(size=15),
legend.text = element_text(size = 15),
plot.title = element_text(size=20),
strip.text = element_text(size=18),
axis.title.x = element_text(size=18),
axis.title.y = element_text(size=19),
axis.text.x = element_text(size = 15, colour = 'black', angle = 0),
axis.text.y = element_text(size = 15, colour = 'black', angle = 0),
legend.position = "right",
panel.background = element_rect(fill = "#333333"),
panel.grid.major = element_line(colour = "#454545"),
panel.grid.minor = element_line(colour = "#454545"))+
ylim(0,4)+
scale_x_datetime(lim = c(as.POSIXct("2013-04-23 10:00:00", format="%Y-%m-%d %H:%M:%S"),as.POSIXct("2013-04-23 14:30:00", format="%Y-%m-%d %H:%M:%S")))+
xlab("time")+
ylab("rate")+ ggtitle("Point, Bin Length and 95% CI")
The graph's legend can be improved. Specifically, the elements in the legend for geom_segment() and geom_point() overlap while none of the elements for geom_pointrange() are displayed:
Can "point" and "bin length" icons be separated so they do not overlap while adding the the "confidence interval" to the legend? More specifically, the geom_segment() and geom_point() elements in the legend should not overlap. The geom_pointrange() elements should be displayed in the legend as well. Thanks for any help!
EDIT 9/16/2013: Here's a graph with the sort of legend that I'd like to create:

Resources