How to fit the axis title with two lines in R? - r

I made one graph with 'two line' y-axis title using the code ylab(expression(paste()
Genotype <- c("CV1","CV2","CV1","CV2")
Category<- c("GN","GN","AGW","AGW")
mean <- c(1.47,1.66,0.98,0.93)
se<- c(0.10,0.20,0.03,0.06)
DataA<- data.frame(Genotype,Category,mean,se)
DataA
ggplot(data=DataA, aes(x=Genotype, y=mean, fill=Category))+
geom_bar(stat="identity",position="dodge", width = 0.7) +
geom_errorbar(aes(ymin= mean-se, ymax=mean + se), position=position_dodge(0.7),
width=0.2, size=1) +
scale_fill_manual(values= c ("Dark gray", "Cadetblue")) +
scale_y_continuous(breaks = seq(0,2,0.2), labels = scales::percent, limits = c(0,2)) +
geom_hline(yintercept=1, linetype="dashed", color = "Dark red", size=1.5) +
xlab("Cultivar") +
ylab(expression(paste("Value of thinning treatment \n relative to unthinning treatment"))) +
theme(axis.title = element_text (face = "plain", size = 15, color = "black"),
axis.text.x = element_text(size= 15),
axis.text.y = element_text(size= 15),
axis.line = element_line(size = 0.5, colour = "black"))+
windows(width=7, height=5)
The y-axis title was divided into two lines, but the whole title was not fitted inside the graph. Even though I adjust the width of graph size, it was not applied to the axis title.
Could you tell me how to fit the whole y-axis title inside the graph well, maintaining the size of axis title (i.e. font size= 15)?
Thanks,

One way would be to adjust the margins giving more space to the left.
library(ggplot2)
ggplot(data=DataA, aes(x=Genotype, y=mean, fill=Category))+
geom_bar(stat="identity",position="dodge", width = 0.7) +
geom_errorbar(aes(ymin= mean-se, ymax=mean + se), position=position_dodge(0.7),
width=0.2, size=1) +
scale_fill_manual(values= c ("Dark gray", "Cadetblue")) +
scale_y_continuous(breaks = seq(0,2,0.2), labels = scales::percent, limits = c(0,2)) +
geom_hline(yintercept=1, linetype="dashed", color = "Dark red", size=1.5) +
xlab("Cultivar") +
ylab(expression(paste("Value of thinning treatment \n relative to unthinning treatment"))) +
theme(axis.title = element_text (face = "plain", size = 15, color = "black"),
axis.text.x = element_text(size= 15),
axis.text.y = element_text(size= 15),
axis.line = element_line(size = 0.5, colour = "black")) +
theme(plot.margin=unit(c(1,0.5,0.5,1.2),"cm"))

Related

Plot stacked barplot with upper part with alpha

I want to plot a stacked bar where the upper part is colored in the same way but with alpha. The images below give an idea, what I want is to have the magma colors, but the upper part with alpha. I wonder if it helps more to have two plots and "stack" them together. The upper part (alpha) is the tam_loc variable in the dataset. That is rural areas.
If I put alpha in aes it produces the output, but I cannot manipulate the alpha degree. Further, if I do this the legend now has a bar (mean value) for non alpha values. See image
The data is here.
My code looks like this:
ggplot(locPCP, aes(reorder(x=NOMGEO, -mean),y=mean, fill=bin, alpha=tam_loc)) +
geom_bar(stat="identity") +
scale_fill_manual(labels = c("> 8", "3.5 - 4", "3 - 3.5", "2.5 - 3", "2 - 2.5", "< 2"),
values = c(state_colors[2:7])) +
scale_x_discrete(name="State") +
scale_y_continuous(name="Emissions per capita (t CO2eq/year)", limits=c(0, 15)) +
geom_hline(yintercept=pcp2015, linetype="dashed",
color = "black", size=1) +
geom_hline(yintercept=pcp2030, linetype="dashed",
color = "red", size=1) +
geom_hline(yintercept=pcp2018, linetype="dashed",
color = "blue", size=1) +
theme_classic() +
theme(legend.position="top",
legend.text = element_text(size=15, color="black"),
legend.title = element_text(size=15, color="black"),
axis.text.x = element_text(size=15, color="black", angle = 90, vjust = 0.2, hjust=1),
axis.text.y = element_text(size=15, color="black"),
axis.title.x = element_text(size=15, color="black", vjust=-1),
axis.title.y = element_text(size=15, color="black")) +
geom_errorbar(aes(ymax=meanS, ymin=meanS), colour="white", width=0.5, size=1) # http://www.cookbook-r.com/Graphs/Lines_(ggplot2)/
You would simply map alpha to tam_loc and specify a scale_alpha_manual scale. Specify guide = "none" inside the alpha scale if you don't want it to appear in the legend. If you want a guide without the horizontal bar, use key_glyph = draw_key_blank inside geom_errorbar, which is where this line is coming from.
Remember, every fill color has an alpha value. A completely solid color that you cannot see through has an alpha value of 1, and a completely invisible color has an alpha of 0. It becomes confusing when you start to talk about the upper parts of the bars "having alpha" - it's more accurate to say that the upper bars have a lower alpha value.
ggplot(locPCP, aes(reorder(x=NOMGEO, -mean), y = mean, fill = bin,
alpha = tam_loc)) +
geom_col() +
geom_hline(yintercept = pcp2015, linetype = "dashed",
color = "black", size = 1) +
geom_hline(yintercept = pcp2030, linetype = "dashed",
color = "red", size = 1) +
geom_hline(yintercept=pcp2018, linetype="dashed",
color = "blue", size = 1) +
geom_errorbar(aes(ymax = meanS, ymin = meanS), colour = "white",
width = 0.5, size = 1, key_glyph = draw_key_blank) +
scale_fill_manual(labels = c("> 8", "3.5 - 4", "3 - 3.5",
"2.5 - 3", "2 - 2.5", "< 2"),
values = c(state_colors[2:7])) +
scale_x_discrete(name = "State") +
scale_y_continuous(name = "Emissions per capita (t CO2eq/year)",
limits = c(0, 15)) +
scale_alpha_manual(values = c(0.5, 1), name = 'Location') +
theme_classic(base_size = 15) +
theme(legend.position = c(0.5, 1),
legend.box = 'vertical',
legend.direction = 'horizontal',
legend.justification = c(0.5, 1),
axis.text.x = element_text(angle = 90, vjust = 0.2, hjust = 1),
axis.text.y = element_text(size = 15, color="black"),
axis.title.x = element_text(vjust = -1))
Incidentally, you have some variables defined in your code that are not present in your question. I have guessed at them here.
state_colors <- viridisLite::magma(8)
pcp2015 <- 5
pcp2018 <- 3
pcp2030 <- 2.5

How to draw an inclined line and parallelly put the text on it in ggplot?

Now, I'm making some hypothesis graph and I made this graph.
x<- c(1,2,3,4,5,6,7,8,9,10,11)
y<- c(100,90,80,70,60,50,40,30,20,10,1)
a<- c(1,2,3,4,5,6,7,8,9,10)
b<- c(1,4,9,16,25,36,49,64,81,100)
dataA<- data.frame (x,y)
dataB<- data.frame (a,b)
geom_line(data=dataA, aes(x=x, y=y), col="Dark red", size=1) +
geom_line(data=dataB, aes(x=a, y=b), col="Dark blue", size=1) +
scale_x_continuous(breaks = seq(0,12,1), limits = c(0,12)) +
scale_y_continuous(breaks = seq(0,120,10), limits = c(0,120)) +
geom_hline(yintercept=70, linetype="dashed", color = "Black", size=1) +
geom_hline(yintercept=50, linetype="dashed", color = "Black", size=1) +
#geom_text(aes(fontface=6), x=11, y=110, label=paste("% distal\n","grains"), size=6, col="Dark blue") +
geom_text(aes(fontface=6), x=10, y=75, label="AGW (90th percentile)", size=5, col="Black") +
geom_text(aes(fontface=6), x=10, y=55, label="AGW (10th percentile)", size=5, col="Black") +
xlab(bquote('x ('~m^2*')')) +
ylab(bquote('y (mg '~grain^-1*')')) +
theme(axis.title = element_text (face = "plain", size = 18, color = "black"),
axis.text.x = element_blank(), #element_blank()) element_text(size= 14)
axis.text.y = element_blank(),
axis.ticks.x = element_blank(),
axis.ticks.y = element_blank(),
axis.line = element_line(size = 0.5, colour = "black"))+
windows(width=5.5, height=5)
As an alternatives, I need to present such as below graph, but I don't know how to draw an inclined line, starting a specific point of y-axis. Also, I would like to add a text on the line in a parallel position. Could you tell me how I can do this?
Many thanks!!
Here is a concrete example based on #Waldi 's comment:
library(ggplot2)
# Change line to what you want
line <- data.frame(x = c(10,30), y = c(300,50))
line = lm(formula = line$y ~ line$x)$coefficients
# ratio required for unequal axis scales
ratio <- 1/15
# get angle of the line
angle <- atan(line[2] * ratio) * 180 / pi
# plot it
ggplot(mtcars, aes(x = mpg, y = hp)) +
geom_point() +
geom_abline(slope = line[2], intercept = line[1], color = "blue") +
coord_equal(ratio = ratio) +
annotate(
geom = "text",
x = 20,
y = 20 * line[2] + line[1],
label = "My Line",
color = "blue",
angle = angle,
vjust = -1 # offset so text isn't directly on the line
)

R ggplot geom_text wipes out background--bug?

I found an issue with ggplot2::geom_text() when I attempt to highlight my data with labels. My MWE illustrates the situation. After I define the plot I add the theme() from phase#1 which colors the panel and plot backgrounds. The red/green is for emphasis. When the labels are added in phase#2, the plot.background goes to white and the panel background to the default grey. Is this something I'm doing, is this an undocumented feature of ggplot2, or is this a bug?
require(ggplot2)
SESnow <- data.frame(Year=c(1978,1988,1995,2000,2013,2017),
Snow=c(355.9,322.1,329.1,303.6,318.5,304.0))
p <- ggplot(SESnow, aes(x=Year, y=Snow, fill=Snow)) +
geom_col(width=1) +
scale_fill_gradient(low="blue", high="red", limits=c(0,400)) +
theme(axis.title.y=element_text(angle=0)) +
ggtitle("Yearly Total Snowfall (inch)") +
labs(subtitle = "Copper City 2019",
caption="Source: Keweenaw County",
x="Snow Season") +
theme(legend.position="none")
#phase#1
p + theme( panel.background = element_rect(fill = "green",
colour = "black",
size = 0.5, linetype = "solid"),
plot.background = element_rect(fill = "blue",
colour = "black",
size = 0.5, linetype = "solid"),
axis.text.x = element_text(colour="grey20",size=11, vjust=1,
margin=margin(t=0,b=0),face="bold"),
axis.text.y = element_text(colour="grey20",size=11, hjust=1,
margin=margin(t=10,b=10),face="bold") )
#phase#2
p + geom_text(data=SESnow, aes(label = Snow, fill=NULL ), y = SESnow$Snow + 20.0,
label=format(SESnow$Snow, digits=2), size=3, fontface="bold",
color="black")
Also note that if you run phase#1 after phase#2 the labels disappear, so this feature is consistent. How do I get a plot with labels and colored background?
The answer is simple. You are generating two plots instead of one. You need to store the plot in p if you want to use the same plot and modify it later.
#phase#1
p <- p + theme( panel.background = element_rect(fill = "green",
colour = "black",
size = 0.5, linetype = "solid"),
plot.background = element_rect(fill = "blue",
colour = "black",
size = 0.5, linetype = "solid"),
axis.text.x = element_text(colour="grey20",size=11, vjust=1,
margin=margin(t=0,b=0),face="bold"),
axis.text.y = element_text(colour="grey20",size=11, hjust=1,
margin=margin(t=10,b=10),face="bold") )
#phase#2
p + geom_text(data=SESnow, aes(label = Snow, fill=NULL ), y = SESnow$Snow + 20.0,
label=format(SESnow$Snow, digits=2), size=3, fontface="bold",
color="black")
Assign the value to p before you use it again. This will solve the issue.
Edit: I am attaching the graph. I guess this is what you wanted.

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.

Relative legend position in ggplot

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

Resources