Add secondary axis ggplot - line chart with two variables - one data frame - r

I used ggplot to make a like graph with two variables, but I need to add a secondary y-axis and assign it to one of the variables ("volt").
I also would like to specify the range of the secondary y-axis (upper and lower limit), as well as the breaks - as I did for the y-main-axis.
My two variables are "Sr" and "volt".
I don't want to use different dataframes and then merge the graphs.
Do any of you know how to do it?
Oh, I must add that I am an absolute beginner!
Thanks,
Pedro
ggplot(data = k, aes(x = Dist)) +
geom_line(aes(y = Sr), colour="blue") +
geom_line(aes(y = volt), colour = "grey") +
xlab(bquote('Distance-um')) +
ylab(bquote('Sr87Sr86')) +
geom_point(aes(y = Sr), colour="black", size=2) +
geom_point(aes(y = volt), colour="grey", size=2) +
theme(axis.title.x = element_text(colour="black",size=10,face="bold"),
axis.title.y = element_text(colour="black",size=10,face="bold"),
axis.text.x = element_text(colour="black",size=8, face="plain"),
axis.text.y = element_text(colour="black",size=8, face="plain")) +
theme(panel.background = element_rect(fill = "white")) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
strip.background = element_blank(),
panel.border = element_rect(colour = "black", fill="transparent")) +
theme(plot.title = element_text(lineheight=.8, size=10, face="bold")) +
geom_hline(aes(yintercept=0.7061), colour="black", linetype="dotted") +
geom_hline(aes(yintercept=0.7078), colour="black", linetype="dotted") +
geom_hline(aes(yintercept=0.70467), colour="black", linetype="dotted") +
scale_x_continuous(limits=c(-0.01, 1000), breaks=c(0, 250, 500, 750, 1000))+
scale_y_continuous(limits=c(0.7039, 0.7101), breaks=c(0.7040, 0.7050,
0.7060, 0.7070, 0.7080, 0.7090)) +
theme(plot.margin = unit(c(.25,.25,.0,.0), "cm"))

First, I would like to mention that two axis is not the best idea.
Having said that, if you still want two axis, you have to scale one of your variables (volt in this case).
Dist<-seq(1,10)
Sr<-c(0.704, 0.705, 0.706, 0.707, 0.708, 0.704, 0.705, 0.706, 0.707, 0.708)
volt<-c(3,5,10,8,12,4,11,3,14,22)
k<-data.frame(Dist,Sr,volt)
k$volt<-k$volt/10
Now, fixing the data makes things easier for plotting, just melt your variables
library(reshape)
k_melt<-melt(k,id="Dist")
And plotting. With sec_axis you can create the second axis and rescale again the values
ggplot(k_melt, aes(x=Dist, y=value, fill=variable, colour=variable))+
geom_line(stat='identity', size=0.5)+
geom_point(stat='identity', size=2)+scale_color_manual(values=c("blue", "grey")) +
scale_y_continuous("SR", sec.axis = sec_axis(~ . *10, name = "Volt"))`
NOTE: You can add your theme and geom_hline to this code. they don't work for the simulated data I created

Related

Can't add legend into my graph on ggplot, Why is this the case?

I want to add a legend it shows black for the 7 day moving average and blue for the bars(daily cases). so it looks something similar to the NHS graph , but the legend does not work when i add it into my code?
ggplot(LimerickNew1, aes(x=TimeStamp, y=DailyCCase,Shape=MA7)) +
geom_bar(stat="identity",fill="steelblue") +
geom_line(aes(y=MA7),size=1.5) +
labs( x="", y="Total cases", title="Total Covid Cases for County Limerick 01-03-20 to 01-
06-`20" )+`
theme_bw()+
theme(legend.background = element_rect(fill = "darkgray"),
legend.key = element_rect(fill = "lightblue", color = NA),
legend.key.size = unit(1.5, "cm"),
legend.key.width = unit(0.5,"cm"),
axis.text.x = element_text(face="bold", color="#008000",size=12, angle=0),
axis.text.y = element_text(face="bold", color="#008000",size=12, angle=0),
axis.title.x = element_text(face="bold", size=12, color="black"),
plot.title = element_text( face = "bold", colour = "black", size = 20,, hjust = 0.5))
Without a reproducible example, it's hard to give a more specific answer for your question, but here's a method that expands upon the comment from #teunbrand and should guide you toward showing a legend.
TL;DR - The reason you're not seeing a legend is because you do not have any layers or geoms drawn that have one of the aesthetics mapped to aes(). All aesthetics like color, size, and fill are specified for each geom outside of an aes() function, which means there's no reason for ggplot2 to draw a legend. To get a legend to be drawn, you need to specify the aesthetic inside aes().
Example
Here's an illustrative example that is similar to OP's question.
library(ggplot2)
set.seed(8675309)
df <- data.frame(
x = 1:100,
y = rnorm(100, 10))
df$z <- log(cumsum(df$y))
ggplot(df, aes(x=x)) +
geom_col(aes(y=y), fill='blue', alpha=0.3) +
geom_line(aes(y=z), size=2) +
ylim(0,25) + theme_bw()
Showing a Legend
To get a legend to show, you have to specify one or more aesthetics inside aes(). The fun fact here is that you don't have to specify a column in the dataset when doing this. If you specify a single value, it will apply to the whole dataset, and basically just show a legend key for the entire set of observations. This is what we want.
ggplot(df, aes(x=x)) +
geom_col(aes(y=y, fill="the columns"), alpha=0.3) +
geom_line(aes(y=z, size="the line"), color="black") +
ylim(0,25) + theme_bw()
Formatting
The names come from the values specified in aes(), and the color change is due to default mapping of color values. To get things to look "right", you want to use some theme() elements to:
keep only one name
squish legends together
position on the chart, rather than on the side
The end result is here:
ggplot(df, aes(x=x)) +
geom_col(aes(y=y, fill="the columns"), alpha=0.3) +
geom_line(aes(y=z, size="the line"), color="black") +
ylim(0,25) +
scale_fill_manual(values="blue") + # recolor the columns
guides(
fill=guide_legend(title="My Legend", order=1),
size=guide_legend(title=NULL, order=2)
) +
theme_bw() +
# legend placement and spacing
theme(
legend.title = element_text(margin=margin(b=10)),
legend.spacing.y = unit(-3,'pt'),
legend.position = c(0.8, 0.8)
)

Adding a Legend in ggplot2

I have the following code.
Financial_Wealth.lq,Financial_Wealth.uq,Total_Wealth.lq,Total_Wealth.uq,time=seq(0,(sPar.dNN),1))
ggplot(data, aes(x=time)) +
geom_line(aes(y = Human_Capital.mean), color="red", size=1) +
geom_line(aes(y = Financial_Wealth.mean), color="goldenrod3", size=1) +
geom_ribbon(aes(ymin=Financial_Wealth.lq, ymax = Financial_Wealth.uq), alpha=0.4, fill="goldenrod3") +
geom_line(aes(y = Total_Wealth.mean), color="dodgerblue", size=1)+
geom_ribbon(aes(ymin=Total_Wealth.lq, ymax=Total_Wealth.uq), alpha=0.4, fill = "dodgerblue") +
scale_x_continuous(name = 'Age',
breaks=(c(seq(0,(sPar.dNN),4))))+
scale_y_continuous(name = 'Wealth Level',
breaks = seq(0,100,10))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
legend.title = element_text(size=12, face="bold"),
legend.text = element_text(size=12),
axis.title = element_text(size=12),
axis.text = element_text(size=10)) +
coord_cartesian(xlim = c(0,45), ylim = c(0,100), expand = TRUE)+
scale_fill_manual(name="Median",values=c("goldenrod3", "red","dodgerblue"),
labels = c("Financial Wealth", "Human Capital", "Total Wealth"))+
ggtitle('Optimal Wealth Development')
You can interpret each data input as a vector of numbers of equal length. Can someone please tell me why the legend is not appearing? What do I need to do differently! Thanks in advance :) I have attached the image that it is producing so you get an idea of what I am trying to achieve.
In order to add a legend, you need to specify one of the aesthetics within aes(). In this case, take all of your geom_line() calls and place for each one the color= inside of aes(). The value assigned to color= within aes() will be the text of the label in the legend: not the color. To assign color, you need to add scale_color_manual() and set values= a named vector.
See below for the following changes that should solve your problem, although in the absence of your dataset or a reprex, I'm unable to test the function of the new code.
# original code
... +
geom_line(aes(y = Human_Capital.mean), color="red", size=1) +
geom_line(aes(y = Financial_Wealth.mean), color="goldenrod3", size=1) +
geom_line(aes(y = Total_Wealth.mean), color="dodgerblue", size=1)+
# new plot code
... +
geom_line(aes(y = Human_Capital.mean, color="Human Capital Mean"), size=1) +
geom_line(aes(y = Financial_Wealth.mean, color="Financial Wealth Mean"), size=1) +
geom_line(aes(y = Total_Wealth.mean, color="Total Wealth Mean"), size=1) +
scale_color_manual(values=c(
"Human Capital Mean"="red",
"Financial Wealth Mean"="goldenrod3",
"Total Wealth Mean"="dodgerblue"))

Can't get r code for show %s and colors for grouped bar chart

I've look up so many sample code snippets online but for the life of me I cannot figure out what I'm doing wrong. I've included the r code below that gives me this chart:
It's generally working, except:
I can't get it to show %s instead of counts (for the factor variable "doctorate"), and
The colors for "group" show up in the legend, but not in the bars themselves.
pg_doc <- ztemp.pg %>%
ggplot(aes(doctorate, group = group)) +
geom_bar(aes(y = ..prop.., fill = group), stat="count") +
geom_bar(position = position_dodge(preserve = "single")) +
scale_fill_manual(values=c("grey45","goldenrod2")) +
theme(legend.position = "bottom",
legend.title=element_blank(),
text = element_text(color="black"), #for x & y axis text labels
axis.text.x = element_text(color="black", size=10, hjust=1),
axis.text.y = element_text(color="black"),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
plot.title=element_text(hjust=.5))+
ggtitle("Highest degrees attained by leadership")+
scale_x_discrete(labels= c("Other", "Doctorate"))
pg_doc
Just write one geom_bar. You can also move fill argument to the aes command in ggplotfunction. To show percentages, you have to calculate them apriori and plot. A simple reproducible example will provide more clarity.
pg_doc <- ztemp.pg %>%
ggplot(aes(doctorate, group = group)) +
geom_bar(aes(y = ..prop.., fill = group), stat="count",position = position_dodge(preserve = "single")) +
scale_fill_manual(values=c("grey45","goldenrod2")) +
theme(legend.position = "bottom",
legend.title=element_blank(),
text = element_text(color="black"), #for x & y axis text labels
axis.text.x = element_text(color="black", size=10, hjust=1),
axis.text.y = element_text(color="black"),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
plot.title=element_text(hjust=.5))+
ggtitle("Highest degrees attained by leadership")+
scale_x_discrete(labels= c("Other", "Doctorate"))
pg_doc

Combine two plots in ggplot?

I need to create a ggplot that is a column plot overlayed with a line plot. The line plot shows mean values, while the column plot shows how the mean values relate to benchmark values. I've managed to create two separate plots in ggplot, but I'm having trouble combining them.
My line plot looks like this:
And is created using this code:
benchMarkLine <- ggplot(UEQScores, aes(x=Scale, y=Score, group=1)) +
geom_line(size = 1.4, colour = "black") +
geom_point(size = 2.4, colour = "black") +
scale_y_continuous(name = "Score", breaks = seq(0, 2.5, 0.25), limits = c(0, 2.5)) +
scale_x_discrete(name = "Scale") +
ggtitle("Mean Scores") +
theme_bw() + # Set black and white theme +
theme(plot.title = element_text(hjust = 0.5, size=10), # Centre plot title
panel.grid.major = element_blank(), # Turn off major gridlines
panel.grid.minor = element_blank(), # Turn off minor gridlines
axis.title.x = element_text(size=10),
axis.text.x = element_text(angle=30, vjust=0.6),
axis.title.y = element_text(size=10))
benchMarkLine
My Column plot looks like this:
And was created with the following code:
benchmarkColPlot <- ggplot(benchmark_long, aes(x=factor(Scale, scaleLevels), y=value, fill=factor(cat, bmLevels))) +
geom_col(position="fill") +
scale_fill_manual(values = bmColours) +
scale_y_continuous(name = "Score", breaks = seq(-1.0, 1.0, 0.25), limits = c(-1, 1)) +
scale_x_discrete(name = "Scale") +
ggtitle("Benchmark Scores") +
theme_bw() + # Set black and white theme +
theme(plot.title = element_text(hjust = 0.5, size=10), # Centre plot title
panel.grid.major = element_blank(), # Turn off major gridlines
panel.grid.minor = element_blank(), # Turn off minor gridlines
axis.title.x = element_text(size=10),
axis.text.x = element_text(angle=30, vjust=0.6),
axis.title.y = element_text(size=10),
legend.title = element_blank())
benchmarkColPlot
How can I combine these two? I tried inserting geom_line(UEQScores, aes(x=Scale, y=Score, group=1)) + above geom_col(position="fill") + in the column plot code, but I just get the following error:
Error: `mapping` must be created by `aes()`
How do I combine these two plots?
OK, I've given up on this - I just created the chart in Excel as it seems to be a bit easier for what I'm doing here.

ggplot2 Boxplot value 0 grid color and line type

I am wondering how I can change the grid line on x value=0, marked with a cross in the image, in my graph to shows the change from +ive to -ive. I would like to have it marked red with the same thickness. Thank you
=== Updated based on the comment
#Mtoto: My apologies. Here is the script.
df.boxplot<- ggplot(melt(df[,c(2:7)]), aes(variable, value))
df.boxplot +
geom_boxplot(lwd=1.2)+ theme_economist() + scale_colour_economist()+
scale_y_continuous(minor_breaks=seq(-5, 10, 0.5),name="Linear Measurements (mm)", breaks=seq(-5, 10, 1)) +
theme(axis.title.x = element_text(face="bold", colour="Black", size=20),
axis.text.x = element_text(face="bold", colour="Black", vjust=0.5, size=20)) +
scale_x_discrete(name="",labels=c("T0 A","T1 B","Δ AB","T0 C","T1 D","Δ CD")) +
theme(axis.title.y = element_text(face="bold", colour="Black", size=30,margin=margin(0,20,0,0)),
axis.text.y = element_text(angle=90, vjust=1, size=20)) +
theme(panel.grid.minor = element_line(colour="White",size=0.2))+
theme(axis.ticks = element_blank())+
ggtitle(" Title")+
theme(plot.title = element_text(size=25,lineheight=2, hjust =0.5, vjust=0.5, margin = margin(20, 10, 20, 0)))
I would also like to add a gap (one x unit/level) between the first three boxplots and the second three boxplots. I tried adding a NA column and use drop=FALSE and it didn't work.
I think you want to look at geom_hline -- I'm sure this is a duplicate...
library(ggplot2)
df <- data.frame(x = gl(5, 25),
y = rnorm(125))
ggplot(df, aes(x, y)) +
geom_boxplot() +
geom_hline(aes(y_intercept = 0), color = "red")

Resources