Relative legend position in ggplot - r

this is my small script in order to make some batch plot in ggplot:
by(database_per_grafici, database_per_grafici$variable, function(i){
ggplot(subset(i, !is.na(value)))+
stat_ecdf(aes(x=value, color=gruppo), size=2)+
scale_y_continuous(labels = percent) +
theme_bw() +
theme(panel.grid.major = element_line(colour = "black", size= 0.3))+
theme(legend.text = element_text(size = 60)) +
theme(legend.justification=c(1,0), legend.position=c(1,0))+
theme(legend.title=element_blank()) +
theme(axis.text.x = element_text(size=16)) +
theme(axis.title.x = element_text(size=20))+
xlab("mg/kg")+
theme(axis.text.y = element_text(size=16)) +
theme(axis.title.y = element_blank()) +
guides(colour = guide_legend(override.aes = list(size=10))) +
ggsave(sprintf("%s.png", unique(i$variable), width = 30,
height = 20, units = "cm"))
})
but there is a problem with the legend as you can see in the two following pictures:
and
the problem is that in some plots, the legend overlays the plot itself.
Is there a way to set the legend position according to the dataframe values?
Thanks

Related

Draw a vertical line from x axis straight up ggplot

I am trying to plot my ggplot with a vertical line that goes from 0 on the x-axis and straight up. I have tried to use geom_line, but I don't seem to get it to work. I would like something similar to the figure. This is my code so far.
ggplot(dat_plot, aes(x = values, y = ind, fill = "lightgrey", width = 0.5)) +
stat_summary(fun.data = quantiles_95, geom = "boxplot") +
ggtitle("Wild boar") +
ylab("") +
xlab("Effect") +
scale_y_discrete(labels = faktorer_vs) +
theme_classic() +
theme(legend.position = "none", axis.text = element_text(size = 10),
axis.title = element_text(size = 13), axis.line = element_line(colour = "black"),
plot.title = element_text(size = 18))

How to show only one horizontal line for a specific axis value in R chart - ggplot2

I have created a R visualisation in Power BI and looking at having only 1 grid line where the horizontal axis value crosses the axis value at 1.
I am not good with words and not sure if I have explained it well in words. Please see the screenshots below to get a better understanding of what I want to achieve.
Any help is greatly appreciated.
First screenshot is from Excel where I was able to do it and I want to replicate the same in the R chart (second screenshot)
library(ggplot2)
ggplot(unique(dataset), aes(x = reorder(Condition, Rate), y = Rate)) +
labs(x = "Condition")+
geom_point(size = 5, stroke = 0, shape = 18, colour="brown") +
geom_point() + geom_line() +
geom_errorbar(aes(ymin = LL, ymax = UL), width=.2, position=position_dodge(.9), colour="brown", alpha=0.6, size=.7) +
theme_bw()+
theme(panel.grid.major = element_blank()) +
theme(axis.text.x = element_text(angle=90, hjust = 1))+
theme(axis.text.x = element_text(size = 10))
Let p is your original ggplot object
step 1: remove the original x axis
p + theme(axis.line.x = element_blank(),
axis.ticks.x = element_blank(),
axis.text.x = element_blank()) +
labs(x = '') -> p1
step 2: add a line at 1
p1 + geom_hline(yintercept = 1, color = "black")
As you have not provided any data, so I am using iris dataset. You can use the following code
library(ggplot2)
ggplot(unique(iris), aes(x = Species, y = Petal.Width)) +
labs(x = "Condition")+
geom_point(size = 5, stroke = 0, shape = 18, colour="brown") +
geom_point() + geom_line() +
theme_bw()+
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
theme(axis.text.x = element_text(angle=90, hjust = 1))+
theme(axis.text.x = element_text(size = 10)) +
geom_abline(slope=0, intercept=1, col = "darkblue",lty=1,size = 0.5)

add labels to stacked bar chart with proportions using ggplot

I am trying to include labels to a stacked bar chart for proportions. I have been able to create the chart but I haven't been able to successfully add the labels. I've gotten labels but they are centered and overwriting one another....I know this has been asked, but I haven't found a solution that works.
The data is tidy in the sense that it is long
ggplot(data=dat) +
geom_bar(stat="identity",
mapping = aes(x=Vintage, y=OrigAmt, fill=fct_rev(Grade)),
position = "fill") +
ggtitle("Proportions by Grade") +
scale_fill_manual(values = c("grey", "gray40", "black")) +
guides(fill = guide_legend(reverse = TRUE, title="Grade")) +
scale_y_continuous(name="Proportion",label=percent_format()) +
theme_bw() +
theme(plot.title = element_text(hjust=0.5),
panel.border = element_blank(),
panel.grid = element_blank(),
axis.text.x = element_text(angle = 90))
Try adding this after geom_bar
geom_text(aes(y = cumsum(OrigAmt)-OrigAmt/2, label = Grade), show.legend = F)
Changing the y to a cumulative summation (cumsum) of the y variable minus half the y variable places the text in the middle of each section of each bar.
You can also add a color aesthetic and maybe turn Grade into a factor with defined color values
This appears to work.
ggplot(data = dat,
aes(y = freq, x = Vintage, fill = fct_rev(Grade))) +
geom_col() +
geom_text(aes(label = paste0(freq,"%")),
position = position_stack(vjust = 0.5), size = 2) +
scale_y_continuous(
labels = dollar_format(suffix = "%", prefix = "")) +
labs(title = "Distribution by Vintage",
subtitle = "xxx") +
labs(x = NULL, y = "Percentage") +
theme_bw() +
theme(legend.position = "bottom",
legend.direction = "horizontal",
legend.title = element_blank()) +
guides(fill = guide_legend(reverse = T)) +
scale_fill_manual(values = c("grey", "gray40", "brown")) +
theme(axis.text.x = element_text(angle = 90),
axis.text.x.bottom = element_text(vjust = 0.5))
However, I want to change the font colors and I can't see to be able to do that successfully.
For example, I want the label fonts to be BOLD and the font for A and B to be WHITE and the font for C to be BLACK. Thanks!

Saving a dark-themed plot using ggsave() creates white bordering panels

I need my charts to have a dark gray theme to match a presentation style. I also need them to be fixed height, but the widths may vary depending on the length of the labels on the y-axis. When I try to export or save, there are always white side bars in the .jpg or .png file.
Here's some sample code that I use to create the chart (there are some extra theming controls in here that are superfluous to the simplified example, but the resulting chart is basically what I am generating):
library(ggplot2)
bar.font <- 8
title <- "Example"
l_labs <- c("")
x_labs <- c("A","B","C")
ests <- c(.5,.3,.2)
nerrs <- c(.05, .05, .05)
perrs <- nerrs
barchart.data <- data.frame(l_labs, x_labs, ests, nerrs, perrs)
p <- ggplot(barchart.data, aes(x=x_labs, y=ests*100)) +
geom_bar(stat="identity", color="#808080", position=position_dodge(), width=0.85, fill="#808080") +
geom_text(aes(y=ests*100+perrs*100+1.5, label=sprintf("%1.1f%%", 100*ests)), vjust=0.5, hjust=0, size=bar.font, color="white") +
geom_errorbar(aes(ymin=ests*100-nerrs*100, ymax=ests*100+perrs*100), width=.2, position=position_dodge(.9), color="white", size=0.25) +
labs(title=title, x="", y = "") + theme_classic() +
scale_y_continuous(expand = c(0,0),limits = c(0,115), breaks=c(0, 20, 40, 60, 80, 100)) +
theme(legend.position="none", legend.text = element_text(color = "white")) +
theme(title = element_text(size=18, colour = "white")) +
theme(axis.text = element_text(size=20, color = "white"), axis.line = element_line(color = "white")) +
theme(axis.text.x = element_text(margin=margin(9,0,0,0)),axis.text.y = element_text(margin=margin(0,9,0,0))) +
theme(axis.title = element_text(size=20, color = "white")) +
theme(axis.title.x = element_text(margin = margin(10,0,0,0))) +
theme(axis.ticks = element_line(colour = 'white', size = .5)) +
coord_flip() +
theme(aspect.ratio = 1) +
theme(panel.background = element_rect(fill = "#1e1e1e")) +
theme(legend.justification=c(1,0), legend.position=c(1,0)) +
theme(plot.background = element_rect(fill = "#1e1e1e", color = "#1e1e1e")) +
theme(panel.grid.major.x = element_line(colour = "white",size=0.1, linetype = "dotted"))
ggsave("test.jpg", height=10, units="in")
And here is what the exported .jpg looks like. I cannot specify an exact width because I do not know what it will be for each chart as the widths vary. Thanks for any guidance.
You can set the background color to whatever value you like:
ggsave("test.jpg", height=10, units="in", bg = "#1e1e1e")
This takes care of the white bars.
It may be a bit confusing that the bg option is not mentioned in the ggsave() documentation. That's because it's part of the graphics device, here jpeg(). It is mentioned in the jpeg() documentation.
The reason why there are white bars in the first place is discussed in depth in this post.

Overlay different datasets in same facetted plot in ggplot2

I need to gather two facet columns into one column with ggplot2.
In the following example, I need to overlay the content of the two columns DEG and RAN into one, while giving different colours to DEG and RAN data (small points and smooth line) and provide the corresponding legend (so I can distinguish them as they are overlayed).
I feel my code is not too, too far from what I need, but the relative complexity of the dataset blocks me. How to go about achieving this in ggplot2?
Here's my code so far:
require(reshape2)
library(ggplot2)
library(RColorBrewer)
fileName = paste("./4.csv", sep = "") # csv file available here: https://www.dropbox.com/s/bm9hd0t5ak74k89/4.csv?dl=0
mydata = read.csv(fileName,sep=",", header=TRUE)
dataM = melt(mydata,c("id"))
dataM = cbind(dataM,colsplit(dataM$variable,pattern = "_",names = c("NM", "ORD", "CAT")))
dataM$variable <- NULL
dataM <- dcast(dataM, ... ~ CAT, value.var = "value")
my_palette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))
ggplot(dataM, aes(x=NR ,y= ASPL)) +
geom_point(size = .4,alpha = .5) +
stat_smooth(se = FALSE, size = .5) +
theme_bw() +
theme(plot.background = element_blank(),
axis.line = element_blank(),
legend.key = element_blank(),
legend.title = element_blank()) +
scale_y_continuous("ASPL", expand=c(0,0), limits = c(1, 7)) +
scale_x_continuous("NR", expand=c(0,0), limits = c(0, 100)) +
theme(legend.position="bottom") +
theme(axis.title.x = element_text(vjust=-0.3, face="bold", size=12)) +
theme(axis.title.y = element_text(vjust=1.5, face="bold", size=12)) +
ggtitle("Title") + theme(plot.title = element_text(lineheight=.8, face="bold")) +
theme(title = element_text(vjust=2)) +
facet_grid(NM ~ ORD)
Here's what it gives me right now:
Extra question: how come DEG/SF doesn't show a smooth line?
You can use the group aesthetic to define that data points with the same value of ORD belong together. You can also map aesthetics shape and color to this variable. You can also use . to specify that the facets are not split along a specific dimension.
I have made the changes to your code below after transforming NR and ASPL to numeric variables:
dataM$NR <- as.integer(dataM$NR)
dataM$ASPL <- as.numeric(dataM$ASPL)
ggplot(dataM, aes(x=NR ,y= ASPL, group=ORD, color=ORD)) +
geom_point(size = .7,alpha = .5, aes(shape=ORD)) + ## increased size
stat_smooth(se = FALSE, size = .5) +
theme_bw() +
theme(plot.background = element_blank(),
axis.line = element_blank(),
legend.key = element_blank(),
legend.title = element_blank()) +
scale_y_continuous("ASPL", expand=c(0,0), limits = c(1, 7)) +
scale_x_continuous("NR", expand=c(0,0), limits = c(0, 100)) +
theme(legend.position="bottom") +
theme(axis.title.x = element_text(vjust=-0.3, face="bold", size=12)) +
theme(axis.title.y = element_text(vjust=1.5, face="bold", size=12)) +
ggtitle("Title") + theme(plot.title = element_text(lineheight=.8, face="bold")) +
theme(title = element_text(vjust=2)) +
facet_grid(NM ~.)

Resources