How to fix ggplot double y axis in r - r

I am trying to make a graph with two y axis. I know there are a lot of other questions out there similar to this but I just cant seem to figure it out based on other posts
So the issue I am having is the y axis scale. Here is what I am doing
Time <- c("June-2018-30", "July-2018-31", "August-2018-31", "September-2018-30",
"October-2018-31", "November-2018-30", "December-2018-31", "January-2019-31",
"February-2019-28", "March-2019-31", "April-2019-30", "May-2019-31")
Bitcoin <- c(3.469861e-17, 3.188903e-17, 2.685114e-17, 2.42335e-17, 2.322641e-17,
2.447058e-17, 3.18029e-17, 2.944836e-17, 2.839419e-17, 2.76008e-17,
2.661607e-17, 2.536966e-17)
`USD Return` <- c(2.35e-13, 2.27e-13, 1.80e-13, 1.60e-13, 1.51e-13, 1.33e-13, 1.18e-13,
1.08e-13, 1.047e-13, 1.09e-13, 1.37e-13, 1.83e-13)
total.values3 <- data.frame(Time, Bitcoin,`USD Return`, stringsAsFactors = F)
library(ggplot2)
ggplot(data=total.values3, aes(x=Time, y=`USD Return`, group=1)) +
geom_line(aes(y = `USD Return`), color = "blue") +
geom_line(aes(y = Bitcoin), color = "red") +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
scale_y_continuous("USD Return",
sec.axis = sec_axis(~./10000, name = "Bitcoin Return")) +
scale_x_date(labels=date_format("%B-%Y-%d"),
date_labels = "%B-%Y", breaks = total.values3$Time)
Here is a picture of what output
I am not sure what is going wrong. I can see that the scale is wrong. I can't figure out why the bitcoin line is just a straight line. I also don't know why the y axis on the right side goes into the negative

total.values3$Time <- as.Date(total.values3$Time, format = "%B-%Y-%d")
ggplot(data=total.values3, aes(x=Time, group=1)) +
geom_line(aes(y = `USD Return`), color = "blue") +
geom_line(aes(y = Bitcoin*10000), color = "red") +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
scale_y_continuous("USD Return",
sec.axis = sec_axis(~./10000, name = "Bitcoin Return")) +
scale_x_date(labels=date_format("%B-%Y-%d"),
date_labels = "%B-%Y", breaks = total.values3$Time)
This should do the trick.

Related

Adding a shaded area to facet

I am really new to R and trying to lean it myself but now I got stuck in a place. I have tried to add a shaded area to a facet but it adds a shaded area to every facet. I wanna highlight a time from 2017-08-08 to 2017-08-16 only and I don't know how to do it.
The code I have right now looks like this:
ggplot(data = Andmed3, aes(x= Aeg, y = arch, group = Prooviala)) +
stat_summary(geom = "errorbar",fun.data = mean_se, aes(group = Prooviala, color = Prooviala)) +
stat_summary(fun = mean,geom="line",lwd=1,aes (group= Prooviala, color = Prooviala)) +
stat_summary(geom = "point", fun = mean, shape = 16, size = 2, aes(color = Prooviala)) +
facet_grid(~Periood, scales = "free_x", space = "free_x") +
labs(x = "KuupƤev", y = "Arhede 16S rRNA geenikoopiate arv")+
theme_bw() +
theme(axis.text.x = element_text(angle = 30, hjust = 1)) +
scale_x_datetime(date_breaks = "1 week", date_labels = " %e %b %y") +
geom_rect(aes(xmin = as.POSIXct('2017-08-08', format = '%Y-%m-%d'),xmax = as.POSIXct('2017-08-16', format = '%Y-%m-%d'),ymin = -Inf,ymax = Inf), alpha = 0.2, fill = 'grey')
I need my graph to look like my second picture but just with the highlighted background in the first facet.
Can someone help me with the code?
Thank You!

R Windrose percent label on figure

I am using the windrose function posted here: Wind rose with ggplot (R)?
I need to have the percents on the figure showing on the individual lines (rather than on the left side), but so far I have not been able to figure out how. (see figure below for depiction of goal)
Here is the code that makes the figure:
p.windrose <- ggplot(data = data,
aes(x = dir.binned,y = (..count..)/sum(..count..),
fill = spd.binned)) +
geom_bar()+
scale_y_continuous(breaks = ybreaks.prct,labels=percent)+
ylab("")+
scale_x_discrete(drop = FALSE,
labels = waiver()) +
xlab("")+
coord_polar(start = -((dirres/2)/360) * 2*pi) +
scale_fill_manual(name = "Wind Speed (m/s)",
values = spd.colors,
drop = FALSE)+
theme_bw(base_size = 12, base_family = "Helvetica")
I marked up the figure I have so far with what I am trying to do! It'd be neat if the labels either auto-picked the location with the least wind in that direction, or if it had a tag for the placement so that it could be changed.
I tried using geom_text, but I get an error saying that "aesthetics must be valid data columns".
Thanks for your help!
One of the things you could do is to make an extra data.frame that you use for the labels. Since the data isn't available from your question, I'll illustrate with mock data below:
library(ggplot2)
# Mock data
df <- data.frame(
x = 1:360,
y = runif(360, 0, 0.20)
)
labels <- data.frame(
x = 90,
y = scales::extended_breaks()(range(df$y))
)
ggplot(data = df,
aes(x = as.factor(x), y = y)) +
geom_point() +
geom_text(data = labels,
aes(label = scales::percent(y, 1))) +
scale_x_discrete(breaks = seq(0, 1, length.out = 9) * 360) +
coord_polar() +
theme(axis.ticks.y = element_blank(), # Disables default y-axis
axis.text.y = element_blank())
#teunbrand answer got me very close! I wanted to add the code I used to get everything just right in case anyone in the future has a similar problem.
# Create the labels:
x_location <- pi # x location of the labels
# Get the percentage
T_data <- data %>%
dplyr::group_by(dir.binned) %>%
dplyr::summarise(count= n()) %>%
dplyr::mutate(y = count/sum(count))
labels <- data.frame(x = x_location,
y = scales::extended_breaks()(range(T_data$y)))
# Create figure
p.windrose <- ggplot() +
geom_bar(data = data,
aes(x = dir.binned, y = (..count..)/sum(..count..),
fill = spd.binned))+
geom_text(data = labels,
aes(x=x, y=y, label = scales::percent(y, 1))) +
scale_y_continuous(breaks = waiver(),labels=NULL)+
scale_x_discrete(drop = FALSE,
labels = waiver()) +
ylab("")+xlab("")+
coord_polar(start = -((dirres/2)/360) * 2*pi) +
scale_fill_manual(name = "Wind Speed (m/s)",
values = spd.colors,
drop = FALSE)+
theme_bw(base_size = 12, base_family = "Helvetica") +
theme(axis.ticks.y = element_blank(), # Disables default y-axis
axis.text.y = element_blank())

How to scale a Geom_bar to be in line with an overlaid line graph in R ggplot

I am trying to overlay a bar chart with a line graph on a single plot with ggplot in R. My line graph works fine but the data are much larger than the data for the bar chart component.
How could I use an additional scale for this bar chart or do something that will get this to look nice all in one graph.
Here is my plot code thus far:
chart <- data.frame("QuantileName" = 1:5, "AvgLoss" = c(100, 500, 1000, 2500, 3000), "AvgFactor" = c(1.0, 1.1, 1.3, 1.4, 1.5))
Plot <- ggplot(chart, aes(x = 1:5)) +
scale_x_continuous(name = "Quintile", limits = c(0, 5 + .5), breaks = seq(1, 5)) +
geom_line(aes(y = AvgLoss, colour = "AvgLoss")) +
geom_bar(aes(y = AvgFactor, colour = "AvgFactor" ), stat = "identity") +
geom_text(aes(y = AvgLoss, label = round(AvgLoss)), position = position_nudge(x = .3)) +
geom_point(aes(y = AvgLoss)) +
ylab("AvgLoss") +
scale_colour_manual("",breaks = c("AvgLoss","AvgFactor"), values = c("AvgLoss" = "red", "AvgFactor" = "grey")) +
ggtitle("Quintile Plot") +
theme(plot.title = element_text(hjust=0.5))
Plot
Thank you for any help!
Essentialy, multiply your AvgFactor variable by a number
+ geom_bar(aes(y = AvgFactor*1000, colour = "AvgFactor" ), stat = "identity")
and set
+ scale_y_continuous(sec.axis = sec_axis(~ ./1000, name = "AvgFactor"))
so your plot code would look like
Plot <- ggplot(chart, aes(x = 1:5)) +
scale_x_continuous(name = "Quintile", limits = c(0, 5 + .5),
breaks = seq(1, 5)) +
geom_bar(aes(y = AvgFactor*1000, colour = "AvgFactor" ),
stat = "identity") +
geom_line(aes(y = AvgLoss, colour = "AvgLoss")) +
geom_text(aes(y = AvgLoss,
label = round(AvgLoss)),
position = position_nudge(x = .3)) +
geom_point(aes(y = AvgLoss)) +
ylab("AvgLoss") +
scale_colour_manual("",breaks = c("AvgLoss","AvgFactor"),
values = c("AvgLoss" = "red", "AvgFactor" = "grey")) +
ggtitle("Quintile Plot") +
theme(plot.title = element_text(hjust=0.5)) +
scale_y_continuous(sec.axis = sec_axis(~ ./1000, name = "AvgFactor"))
However, I think it is probably more elegant to avoid secondary axes whenever possible.
It may be useful to know that geom_col(...) is shorthand for geom_bar(..., stat = 'identity')

ggplot legend / label change with various guides

I am trying to change the labels of a legend on a ggplot where I have legends for 2 aes.
With scale_file_manual, it works, but for one of the two legends only. I guess I should use "guides" that I already used to remove the titles and also remove legend for a 3rd aes, but I do not manage to do it.
Do you have a solution?
Here is my code :
p <- ggplot(data, aes(x = Nb))
p + geom_ribbon(aes(ymin = Sandwich.min, ymax = Sandwich.max, fill = 'grey70',alpha=0.8)) +
geom_ribbon(aes(ymin = Assiette.min, ymax = Assiette.max, fill = '#6495ED80',alpha=0.8)) +
geom_line(aes(y = Pizza, col = '#FF7F24')) +
geom_line(aes(y = Sushis, col = '#228B22')) +
labs(title = "Business lunch cost by number of participants",
x = "Number of participants",
y = "Price (Euros)") +
scale_x_continuous(breaks=seq(1,20,1)) +
scale_y_continuous(breaks = seq(0,300,50)) +
theme_light() +
theme(plot.title = element_text(size = 12, hjust = 0.5)) +
guides(alpha = FALSE, colour = guide_legend(" "), fill = guide_legend(" ")) +
scale_fill_manual(
values=c('#6495ED80','grey70'),
labels=c("Assiettes","Sandwiches"))

Scaling POSIXlt data in histogram using ggplot2

How to change the labels at x-axis in the form "2013-07-01 00:30:00"?
library(ggplot2)
a<-as.POSIXlt("2013-07-01 00:30:00")
b<-as.POSIXlt("2013-07-5 00:30:00")
aI<-as.numeric(a)
bI<-as.numeric(b)
times<-sample(seq(aI,bI,by=2),100)
ggplot(, aes(x=times)) +
geom_histogram(aes(y=..count..),binwidth=10000, colour="black") +
theme(axis.text.x = element_text(angle=45))
And I looking for a function to add a curve like
geom_density(alpha=.2, fill="#FF6666")
but at the plot above, so that the curve fits on the ..count.. property.
You are passing numeric x values to ggplot. You should pass datetime values and use scale_x_datetime:
times <- sample(seq(a, b, by = 2), 100)
library(scales)
ggplot(, aes(x = times)) +
geom_histogram(aes(y= ..count.. ), binwidth = 10000, colour = "black") +
theme(axis.text.x = element_text(angle = 45)) +
scale_x_datetime(labels = date_format("%Y-%m-%d %H:%M:%S"))
You cannot add the density to the plot because the y-axis scales don't fit (neither with the density nor with the counts from stat_density). If you only care about the shape of the density curve you could use geom_density(alpha = .2, fill = "#FF6666", aes(y = ..scaled.. * 7.5)).
Edit:
According to your comment you seem to want this:
ggplot(, aes(x = times)) +
geom_histogram(aes(y= ..density..), binwidth = 10000, colour = "black") +
theme(axis.text.x = element_text(angle = 45)) +
scale_x_datetime(labels = date_format("%Y-%m-%d %H:%M:%S")) +
geom_density(alpha = .2, fill = "#FF6666")
Which is confusing because you specified y = ..count.. explicitly in geom_histogram (although it is the default).

Resources