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.
Related
This question already has answers here:
Place a border around points
(5 answers)
Closed 1 year ago.
I have a dataset like this:
Year<-rep(2001:2005, each = 5)
name<-c("John","Ellen","Mark","Randy","Luisa")
Name<-c(rep(name,5))
Value<-sample(seq(0,25,by=1),25)
mydata<-data.frame(Year,Name,Value)
And my plot looks like this:
p <- ggplot(mydata, aes(x=Year, y=reorder(Name, desc(Name)), size = Value)) +
geom_point(aes(colour = Value,
alpha = I(as.numeric(Value > 0))))
p <- p + scale_colour_viridis_c(option = "D", direction = -1,
limits = c(1, 25)) +
scale_size_area(guide = "none") +
ylab("Name") +
theme(axis.line = element_blank(),
axis.text.x=element_text(size=11,margin=margin(b=10),colour="black"),
axis.text.y=element_text(size=13,margin=margin(l=10),colour="black",
face="italic"),
axis.ticks = element_blank(),
axis.title=element_text(size=18,face="bold"),
panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(),
legend.text = element_text(size=14),
legend.title = element_text(size=18))
I would like to improve it in two ways but I couldn't figure out how.
I would like to add a black border around points. I know I should use pch>20 and specify colour, but because my colours are mapped to a feature of the dataset (they depend on value, in this case), I don't know exactly how to do that. Note that value = 0 points are not plotted. Easy stratagems such as plotting bigger black points under my points seem utopic for me.
I would like to change the breaks of the scale (e.g., instead of having breaks every 5, I'd like to have breaks every 2.5), but it is a continuous scale, and I'm not sure how to do that.
I am not very familiar with ggplo2, thus any help would be appreciated!
You can indeed use a shape >20, e.g. I use shape=21 here. Then you need to change your scale_color_ to scale_fill_, because the color is now black (it is the border of the shape).
For breaks, you could just specify them in the scale itself. Combining both:
ggplot(mydata, aes(x=Year, y=reorder(Name, desc(Name)), size = Value)) +
geom_point(aes(fill = Value,
alpha = I(as.numeric(Value > 0))), shape=21, color = "black") +
scale_fill_viridis_c(option = "D", direction = -1,
limits = c(1, 25), breaks=seq(1, 25, 2.5)) +
scale_size_area(guide = "none") +
ylab("Name") +
theme(axis.line = element_blank(),
axis.text.x=element_text(size=11,margin=margin(b=10),colour="black"),
axis.text.y=element_text(size=13,margin=margin(l=10),colour="black",
face="italic"),
axis.ticks = element_blank(),
axis.title=element_text(size=18,face="bold"),
panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(),
legend.text = element_text(size=14),
legend.title = element_text(size=18))
I would like to use ggplot to plot a graph that looks similar to this, where the axis names (represented as the units) are shown along the axes instead of right in the middle of the axes.
The only R way I can think of is to add a text object, but that may causes alignment inconsistencies if I want to display a few similar graphs together. Editing after the figure has been produced also does not seem elegant because the same editing software's font (say ppt editors) may not look the same as the same font in R.
Is there another way to achieve this? Thanks in advance!
This is what worked for me.
library(ggplot2)
base <- ggplot(economics, aes(date, psavert)) +
geom_blank() +
labs(x="KG", y="%")
base + theme(axis.title.y = element_text(hjust = 1, size = 14), axis.title.x = element_text( hjust = 1, size = 14))
The default values for axis.title.y = element_text( hjust = .5) and axis.title.x = element_text( hjust = .5), and changing the hjust to 0 will bring the axis texts to the co-ordinate point (0,0).
Update
To replicate the background and the arrow, you can do as follows:
# see ?ggplot2::arrow
arrow <- arrow(length = unit(0.5, "cm"), ends = "last", type = "closed")
# -------------------------------------------------------------------------
# A reproducible dataset from ggplot2 (you can use your own data set)
base <- ggplot(economics, aes(date, psavert)) +
geom_blank() +
labs(x="Kg", y="%") +
theme_bw()
# -------------------------------------------------------------------------
# Add a theme layer removing boarder, grid lines and add the axes arrow
base_bg <- base + theme(
panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(arrow = arrow)
)
# -------------------------------------------------------------------------
# finally position the axis title up to the arrow
base_bg + theme(axis.title.y = element_text(hjust = 1, size = 14, face="bold", family = "TT Times New Roman"), axis.title.x = element_text( hjust = 1, size = 14, face = "bold", family="Serif"))
Output
Update - correcting % on Y-axis
#see the addition of angle = 360 on axis.title.y
base_bg + theme(axis.title.y = element_text(hjust = 1, size = 14, face="bold", family = "TT Times New Roman", angle = 360), axis.title.x = element_text( hjust = 1, size = 14, face = "bold", family="Serif"))
Output - label '%' corrected
try:
mop + theme(axis.text.x = element_text(margin=margin(1,2,3,4,"pt"),angle=0)
where 1,2,3,4 indicates the measurements of bottom, left, top, right margins
You can use hjust to move the axis label along the line, with 1 being the max.
p + theme(axis.title.x = element_text(hjust = 1), axis.title.y = element_text(hjust = 1, angle = 0))
enter image description hereI'm reading in a csv file and using ggplot to make a box plot and having issues with the size of the text on the x axis. I can't reduce the text size because I am reducing the over all image for a manuscript and this is the optimal size to make the axes visible. I'd like to have the genotype names below each box plot on the x axis, I've angled genotype names on the axis, but it still doesn't seem to be enough and looks a bit awkward. I'd like to add a line break for at least the longest genotype (4-67/Chrimson), but I don't think I am doing this right. I've tried setting new labels using in the scale_x_discrete and also in the axis.text.x but under both conditions, it either skips over that variable or ignores the command.
FYI: the data frame has two variables, group activity and genotype and genotype has 4 levels.
Thank you in advance!!
Here's my code so far..
dat5=read.csv("Time Point 120 Raw Data C-Test.csv")
plot5<- ggplot(dat5, aes(x = Genotype, y = Group.Activity, col = Genotype, fill = Genotype, ymin= -40, ymax = 50)) +
geom_boxplot(fatten = 1, lwd = .5, alpha = .6) +
# reorder so x-axis is not alphabetical
scale_x_discrete(limits=c("4-67/Chrimson","4-67/+","+/Chrimson", "+/+"))+
scale_fill_manual(values=c("#F99205", "#4ED55F", "#36A6D6", "#5752D0"))+
scale_color_manual(values=c("#F99205", "#4ED55F", "#36A6D6", "#5752D0"))+
geom_beeswarm(size = 1.5, alpha = .75, cex = 3)+
ylab("Percent Activity After Baseline Subtraction")+
theme_classic()+
theme(axis.title.x = element_blank(), axis.text.x = element_text(size = 16, color="black"), axis.ticks.x = element_blank())+
theme(axis.text.y = element_text(size = 24, color="black"), axis.ticks.y = element_blank())+
theme(axis.title.y = element_text (size = 24, color="black"))+
theme(axis.ticks.x = element_blank())+
theme(legend.position = "none")
This might primarily be a result of me misunderstanding how panel.margin = unit(...) works in the theme() function...but I'm unable to customize margins in facet_wrap the way that I'd like. Basically, I want a facet_grid that looks like this, with facet text (i.e. strip.text) inset in each facet and no spcaing between each facet:
(I've left in the pink borders to show the dimensions of each facet)
So here's the code so far.
To set up the data and plot:
library(ggplot2)
library(grid)
p <- ggplot() +
geom_bar(data = mtcars, aes(x = cyl, y = qsec), stat = 'identity') +
facet_wrap( ~ carb, ncol = 3)
mytheme <- theme_minimal() + theme(
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank(),
panel.margin = unit(0, "lines"),
panel.border = element_rect(colour = rgb(1.0, 0, 0, 0.5), fill=NA, size=1)
)
The standard plot
p + mytheme
Removing the strip.text completely
p + mytheme + theme(strip.text = element_blank())
Adding the strip.text and insetting it
p + mytheme +
theme(strip.text = element_text(size = rel(3.0), vjust = -4.0))
The re-inclusion of strip.text (and the increased relative size) increases the vertical margin between the two rows. So at this point, I don't know how to close the vertical gap between the top and bottom rows.
Too much negative margin
p + mytheme +
theme(strip.text = element_text(size = rel(3.0), vjust = -4.0),
panel.margin = unit(c(-2, -2), "lines"))
So how do I target just the panel.margin between the two rows?
Edit: Additional information. The space between the rows appears to be strip.background:
p + mytheme +
theme(strip.text = element_text(size = rel(3.0), vjust = -4.0),
panel.margin = unit(-1, "lines"),
strip.background = element_rect(fill = rgb(0, 1.0, 0, 0.2)))
Among the list of possible arguments to theme(), there is not only panel.margin ("margin around facet panels (unit)", see ?theme), but conveniently, you can also access one of the axes at a time, with panel.margin.x and panel.margin.y respectively ("horizontal/vertical margin around facet panels (unit; inherits from panel.margin)").
Therefore, while decreasing the margin below zero feels a bit like a hack, something like the following will do the job (you might have to adjust the value a little - unit(-2, "lines") worked best for me):
p + theme(strip.text = element_text(size = rel(3.0), vjust = -4.0),
panel.margin.y = unit(-2, "lines"))
If you use strip.text = element_blank(), then you should probably use panel.margin.y = unit(-0.5, "lines").
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: