move y axis labels closer to heatmap (ggplot2) [duplicate] - r

This question already has answers here:
Remove space between plotted data and the axes
(3 answers)
Closed 1 year ago.
I am trying to move my y-axis tick marks closer to my heatmap.
Here is the code for the heatmap:
ggplot(p_typ_meta, aes(SampleType_Basic, Phylum, fill= Counts)) +geom_tile()+
scale_fill_gradient2(low="blue", mid="white",high="red",midpoint=.15)+theme(axis.title.x = element_text(size=13),axis.title.y = element_text(size=13),axis.text = element_text(size=11),axis.text.y=element_text(margin = margin(0,0)),legend.title.align=0.5, legend.title = element_text(size=13),legend.text = element_text(size=11),plot.title = element_text(hjust=0.5, size=15)) +labs(x="Sample Type", y="Microbial Phyla", title="Microbial Phyla & Sample Type",fill="Relative Abundance")+theme_classic()
I have tried the following:
theme(axis.text.y=element_text(hjust=0.5))
theme(axis.text.y=element_text(margin = margin(0,0)))
theme(axis.ticks.margin=unit(0,'cm'))
theme(axis.text.y = element_text(margin = margin(r = 0)))
scale_y_discrete(expand = c(0, 0))
scale_y_continuous(expand=c(0, 0))
Is there something I am missing in my code? Or is this just how heatmaps work in ggplot2?
I have attached the heatmap I made, and the red arrows show where I want to move the y axis labels. Thanks for the insight!

Using scale_x_discrete(expand = c(0,0)) does the trick. Since you want to reduce the space on the x-axis you need to use this scale and not the one for the y axis.

Related

Change axis title position in {ggplot2} [duplicate]

This question already has answers here:
Plot axis name on a different position other than the middle of the axis
(3 answers)
Closed 2 days ago.
The axis titles are normally centered over the axis themselves. How can I change the positions? For example, I want my y-axis title to be on top of the y-axis, and the x-axis title to be on the right of the x-axis. Does anybody know how to do it in R with ggplot2?
Ok, just figured it out. So, for the y-axis, you should set axis.title = element_text(hjust = 1) to be on top, and for the x-axis axis.title = element_text(vjust = 1) to be on the right (which sounds pretty unintuitive to me, given the y-axis is the vertical one). All inside theme(), this is. So, to conclude:
ggplot(data = data, aes(x = x, y = y)) +
geom_point() +
theme(axis.title = element_text(vjust = 1, hjust = 1))

How to add percentages on histogram [duplicate]

This question already has answers here:
Add percentage labels to a stacked barplot
(2 answers)
R ggplot2 stacked barplot, percent on y axis, counts in bars
(1 answer)
Stacked barplot using R base: how to add values inside each stacked bar
(2 answers)
Closed 2 months ago.
I try to add percentages on the percentage histogram, my code is as follows, but it seems that something is wrong, I can't add the percentages to the graph correctly, and I can't get the perfect percentage histogram, please tell me what is wrong.
data<-data.frame(type=c("A","B","C"),
loss=c(1.7,2.2,2.5,0.8,3.1,4.7,0.5,1.5,1.7,0.7,1.4,1.7),
label=c("1","2","3","4"))
data<-data%>%
group_by(type)%>%
mutate(count=sum(loss))%>%
mutate(freq=round(100*loss/count,2))
ggplot(data,aes(label,loss ,fill=type))+
geom_bar(stat="identity",position="fill",alpha = 0.9)+
theme_bw() + theme(panel.grid=element_blank())+
theme(axis.ticks.length=unit(0.5,'cm'),
legend.position = "top")+
scale_y_continuous(labels = scales::percent)+
geom_text(label = paste0(data$freq,"%"))
Your group_by variable must be "label".
Don't multiply variable with 100. Multiply this variable inside paste() function.
Use position_stack() function to center labels.
library(tidyverse)
data<-data.frame(type=c("A","B","C"),
loss=c(1.7,2.2,2.5,0.8,3.1,4.7,0.5,1.5,1.7,0.7,1.4,1.7),
label=c("1","2","3","4"))
data<-data%>%
group_by(label)%>%
mutate(count=sum(loss))%>%
mutate(freq=round(loss/count,2))
ggplot(data,aes(label,freq ,fill=type))+
geom_bar(stat="identity",position="fill",alpha = 0.9)+
theme_bw() + theme(panel.grid=element_blank())+
theme(axis.ticks.length=unit(0.5,'cm'),
legend.position = "top")+
scale_y_continuous(labels = scales::percent)+
geom_text(label = paste0(100*data$freq,"%"), position = position_stack(vjust = 0.5))
In geom_text(), you need to specify position = position_fill(). You will probably also want to adjust the heights so that the text appears in the middle of each bar, which you can do with vjust:
ggplot(data,aes(label,loss ,fill=type))+
...
geom_text(label = paste0(data$freq,"%"),
position = position_fill(vjust = 0.5))

Moving legend to the bottom in ggplot2 [duplicate]

This question already has answers here:
How to move or position a legend in ggplot2
(4 answers)
Closed 7 years ago.
I have created the following heatmap. If you notice that the legend for cohort is on the right and the vertically placed.
How do I move the legend to the bottom in order to give more space for X axis variable month M0 to M55...Also, you will notice that X axis elements are overlapping hence not clear.
Output of the graph:
cohort.clients<-df1
cohort.clients$cohort<-as.character(cohort.clients$cohort)
#we need to melt data
cohort.chart.cl <- melt(cohort.clients, id.vars = 'cohort')
colnames(cohort.chart.cl) <- c('cohort', 'month', 'clients')
#define palette
reds <- colorRampPalette(c('light green',"dark green","yellow"))
#plot data
p <- ggplot(cohort.chart.cl, aes(x=month, y=clients, group=cohort))
p + geom_area(aes(fill = cohort)) +
scale_fill_manual(values = reds(nrow(cohort.clients))) +
ggtitle('Customer Cohort')
Try something like:
ggplot(cohort.chart.cl, aes(x=month, y=clients, group=cohort))
geom_area(aes(fill = cohort)) +
scale_fill_manual(values = reds(nrow(cohort.clients))) +
ggtitle('Customer Cohort') +
theme(axis.text.x = element_text(angle = 45, hjust = 1),
legend.direction = "horizontal", legend.position = "bottom"))
It's also worth noting that your color palette is essentially the same color. If you make cohort$month a factor then ggplot should automatically give you a much more informative palette by default. That being said, with >50 categories, you're well past the realm of a distinguishable colors and might also consider binning the months (into yearly quarters?) and returning to a spectrum like you have now.

Put labels on pie ggplot2 [duplicate]

This question already has answers here:
ggplot, facet, piechart: placing text in the middle of pie chart slices
(4 answers)
Closed 7 years ago.
My df looks like:
1 with score
125 without score
I'd like to make piechart in ggplot:
ggplot(data = df_pp, aes(x = "", y = Number/sum(Number),fill = PolyPhen_score)) + geom_bar(stat="identity") + coord_polar(theta='y') +
ggtitle("Variants with PolyPhen score and without PolyPhen score") +
scale_y_continuous(labels = percent) + labs(x = "", y = "") +
theme(panel.background = element_rect(fill = 'white')) +
geom_text(aes(label = paste(round(Number/sum(Number)*100),"%")),vjust = 5)
But my labels 1% and 99% are overlapped on the piechart.
If I add this code, it doesn't help:
geom_text(aes(y=Number/2 + c(0,cumsum(Number)[-length(Number)]), label = percent(Number/100)), size=5)
Maybe these other Stackoverflow questions can help you:
ggplot, facet, piechart: placing text in the middle of piechart slices
R + ggplot2 => add labels on facet pie chart
I did few tests on my machine with some random data and I tried with this:
geom_text(aes(x = 1.7, y=cumsum(Number/sum(Number)) - Number/sum(Number)/2, label = paste(round(Number/sum(Number)*100),"%")), size = 6)
X is the distance of labels from the center of the pie. x = 1.7 gives me a nice result with my data in RStudio, but probably you will need different values.

Ggplot2: Heatmap + Bar chart combination and tweaking

I'm new to R and am trying to visualise data that is broken down by company and by year for a project at university. I want to try and add bars (as in bar chart bars) to the top and right hand side of the heatmap I've created below, to provide a direct method of comparing count data between the companies (right y axis), and between years for the group as a whole (top x axis).
I know I could probably merge images in Illustrator or something pre-publication, but I know the software is capable of adding together graphics (in a Lattice i think?) and I would like to improve my skills with R and ggplot.
Ideally I would also like to learn to:
1) add the values of each tile superimposed on top
geom_text(aes(fill = trialx.m$value, label = trialx.m$value)
doesn't seem to work for me?
2) Move the legend so that it was out of the way of the bar plots
3) Adjust the legend size and scale (to account for the data scaling)
4) order the heatmap vertically with the bar sizes
I know this is a lot, but I would appreciate help or advice about any part.
What I'm currently doing:
Re-scaling
library(ggplot2)
trialx.m <- melt(trialx)
trialx.m <- ddply(trialx.m, .(variable), transform, rescale = scale(value))
Plotting
(p <- ggplot(trialx.m, aes(variable, Company)) +
geom_tile(aes(fill = rescale), colour = "white") +
scale_fill_gradient(low = "ghostwhite", high = "darkblue"))
Neaten, remove background, rotate text etc.
p + theme_grey(base_size = base_size) + labs(x = "", y = "") +
scale_x_discrete(expand = c(0, 0)) + scale_y_discrete(expand = c(0, 0)) +
opts(legend.position = "", axis.ticks = theme_blank(),
axis.text.x = theme_text(size = base_size * 0.8, angle = 90, hjust = 0,
colour = "grey50"))
Here is a dropbox link to the data I am using:

Resources