R - Plot with two y axis, bars and points not aligned - r

For a customer I'm trying to do a combined barplot and lineplot (with points) with two y axis.
Problem: My bars and points are not aligned.
Background: We have several machines and are measuring their number of on/of switches and the amount of time that each machine is running. We want both information together in one plot to save space, because we have several machines.
The data is aggregated by day or hour. Here's some sample data:
date <- seq(as.Date("2016-10-01"), as.Date("2016-10-10"), "day")
counts <- c(390, 377, 444, NA, NA, NA, NA, 162, 166, 145)
runtime <- c(56.8, 59.4, 51.0, NA, NA, NA, NA, 38.5, 40.9, 43.4)
df <- data.frame(date = date, counts = counts, runtime = runtime)
Here's what I tried so far:
par(mar = c(3,4,4,4) + 0.3)
barplot(df$runtime, col = "palegreen2", border = "NA", ylab = "runtime in [%]",
ylim = c(0,100), font.lab = 2)
par(new = TRUE)
ymax <- max(df$counts, na.rm = TRUE) * 1.05
plot(df$date, df$counts, type = "n", xlab = "", ylab = "", yaxt = "n",
main = "Machine 1", ylim = c(0, ymax))
abline(v = date, col = "red", lwd = 2.5)
lines(df$date, df$counts, col = "blue", lwd = 2)
points(df$date, df$counts, pch = 19, cex = 1.5)
axis(4)
mtext("Number of switching operations", side = 4, line = 3, font = 2)
I found some inspiration for two axis here: http://robjhyndman.com/hyndsight/r-graph-with-two-y-axes/
What can I do to get bars with their middle aligned with the points of the lineplot?

The problem you are running into is the call to the second plot function after the barplot. This is shifting/resizing the plotting canvas which is causing the shift in the subsequent points.
Here is a quick work-around that just rescales the points and lines onto the barplot. It saves the barplot as an object, which stores x-axis locations for the mid-points of the bars. Then, when you plot the abline, lines and points using 'bp' as the x-axis variable, they will be correctly aligned.
ymax <- max(df$counts, na.rm = TRUE) * 1.05
par(mar=c(4.1,5.1,2.1,5.1))
bp <- barplot(df$runtime, col = "palegreen2", border = "NA", ylab = "runtime in [%]",
ylim = c(0,100), font.lab = 2, xlim=c(0.2,12), )
barplot(df$runtime, col = "palegreen2", ylab = "runtime in [%]", border="NA",
ylim = c(0,100), font.lab = 2)
abline(v = bp, col = "red", lwd = 2.5)
lines(bp, df$counts/ymax*100, col = "blue", lwd = 2)
points(bp, df$counts/ymax*100, pch = 19, cex = 1.5)
axis(4,at=c(0,20,40,60,80,100), labels=c("0","100","200","300","400","500"))
mtext("Number of switching operations", side = 4, line = 3, font = 2)
axis(1, at=bp, labels=df$date)

#emilliman: Thank you for your patience and input! Your plot is not completely correct, because the scaling of the second y-axis does not fit the points' values, but your idea helped me to find a solution!
Here's my new code:
library(plyr)
ymax <- max(df$counts, na.rm = TRUE)
ymax_up <- round_any(ymax, 100, f = ceiling)
ylab <- ymax_up/5 * c(0:5)
par(mar = c(3,4,4,4) + 0.3)
bp <- barplot(df$runtime, col = "palegreen2", border = "NA", ylab = "runtime in [%]",
ylim = c(0,100), font.lab = 2, main = "Machine 1")
abline(v = bp, col = "red", lwd = 2.5)
lines(bp, 100/ymax_up * df$counts, col = "blue", lwd = 2)
points(bp, 100/ymax_up * df$counts, pch = 19, cex = 1.5)
axis(4,at=c(0,20,40,60,80,100), labels= as.character(ylab))
mtext("Number of switching operations", side = 4, line = 3, font = 2)
xlab <- as.character(df$date, format = "%b %d")
axis(1, at=bp, labels = xlab)
abline(h = c(0,100))
(http://i.imgur.com/9YtYGSD.png)
Maybe this is helpful for others who run into this problem.

Related

Factor variable on x-axis for double y-axis

Right now on the x-axis it plots numerical variable "1,2,3,4" etc. when instead I want it to graph the game. As you can see in line 85, axis(1,Champ$game) I want the game name on the x-axis, but instead it just numbers the game rather than putting the game name. How do I fix this?
par(mar=c(5, 4, 4, 6) + 0.1)
plot(Champ$daily_max_vel, pch = 16, axes = FALSE, ylim =
c(3.0,3.9),type = "b", col = "black", ylab = "", xlab = "",
main = "Athlete")
##Creates y-axis for graph 1
axis(2, ylim = c(0,1), col = "black", las = 1)
mtext("Velocity (m/s)", side = 2, line = 2.5)
box()
## Allows for second plot on same graph
par(new = TRUE)
#Plotting second graph
plot(Champ$daily_peak_power, pch = 1, xlab = "", ylab = "",
ylim = c(1000,1600), axes = FALSE, type = "b",
col = "orange")
#Creating Second Axis
mtext("Power (W)", side = 4, col = "orange", line = 4)
axis(4,ylim = c(1200,1600), col = "orange", col.axis =
"orange", las = 1)
axis(1,Champ$game)
Using the labels function should do what you are looking for - here is an example of what I think your issue is. If this doesn't work, edit your post to provide your data structure.
# create sample data
df <- data.frame(game = sample(c(1, 2, 3), 150, replace = TRUE),val = rgamma(150, 50))
plot(df)
# label factors
df$game <- factor(df$game, levels = 1:3, labels = c("Game A", "Game B", "Game C"))
# plot
plot(df, axes = F, type = "b")
axis(1, df$game, labels = df$game) # shows game A, game b, game c instead of 1, 2, 3

X Axis not showing up R

I am trying to use two different Y axis with the same X Axis and when I set both axes to false the Year wont show up
library(lubridate)
x <- dataset$Date
y <- dataset$AvgCostPerKwh
z <- dataset$ActualkWhSold
par(mar=c(5, 4, 4, 6) + 0.1)
plot(year(x),y, pch = 16, axes = FALSE, ylim = c(0.030,0.090), xlab = "", ylab = "",
type = "b", col="black", main = "Wholesale Power cost")
axis(2, ylim =(range(c(y))), col = "black", las =1)
mtext("$ per KWh", side = 2, line = 2.5)
box()
par(new = TRUE)
plot(year(x),z, pch = 15, xlab = "", ylab = "",ylim=c(5000000,45000000),
axes = FALSE, type="b", col="red")
mtext("Kwh's Sold", side=4, col="red", line=4)
axis(4, ylim=(range(c(z))), col = "red", las=1)
mtext("Year", side = 1, col="black",line=2.5)
legend("topleft", legend = c("AvgCostPerKwh", "ActualKwhSold"),
text.col = c("black", "red"),
pch=c(15,15),col=c("black", "red"))
Image 1
When I set one of the plots to true, I get overlapping values one one side, but the year on the bottom shows up.
library(lubridate)
x <- dataset$Date
y <- dataset$AvgCostPerKwh
z <- dataset$ActualkWhSold
par(mar=c(5, 4, 4, 6) + 0.1)
plot(year(x),y, pch = 16, axes = TRUE, ylim = c(0.030,0.090), xlab = "", ylab = "",
type = "b", col="black", main = "Wholesale Power cost")
axis(2, ylim =(range(c(y))), col = "black", las =1)
mtext("$ per KWh", side = 2, line = 2.5)
box()
par(new = TRUE)
plot(year(x),z, pch = 15, xlab = "", ylab = "",ylim=c(5000000,45000000),
axes = FALSE, type="b", col="red")
mtext("Kwh's Sold", side=4, col="red", line=4)
axis(4, ylim=(range(c(z))), col = "red", las=1)
mtext("Year", side = 1, col="black",line=2.5)
legend("topleft", legend = c("AvgCostPerKwh", "ActualKwhSold"),
text.col = c("black", "red"),
pch=c(15,15),col=c("black", "red"))
image 2
I am not sure, I have followed other examples on here about 2 Y axis and I can't get mine to work.
I have answered my own question for anyone interested, I forgot to add
year(as.Date(dataset$Date, format = "%m/%d/%Y"),"%Y")
at the top before adding
plot(year(x), y, pch=16, axes=FALSE, ylim=c(0.030,1), xlab="", ylab="",
type="b",col="black", main="Wholesale Power Cost")

How to customise dates (years) on the x-axis in R

I am struggling to customise the jump size on the x-axis in R.
Current code:
par(mfrow = c(2,2))
r.star.ts.sp <- ts(r.star.sp, frequency = 4, start = c(1978,1), end = c(2018, 1))
# Big drop in r* around 123th quarter equivalent to 2008:Q4 / 2009:Q1
trendgrowth.ts.sp <- ts(trendgrowth.sp, frequency = 4, start = c(1978,1), end = c(2018, 1))
plot.ts(r.star.ts.sp,
ylim = c(-3, 4), xlab = " ", ylab = " ", axes = F, col = "blue")
lines(trendgrowth.ts.sp, lty = 2, col = "red")
abline(h = 0, lty = 2)
title(main ="r* and Trend Growth", line = 0.5, font.main = 3)
box()
axis(4)
axis(1)
legend("bottomleft", legend = c("r*", "Trend Growth (g)"),
bty = "n", lty = c(1,2), col = c("blue", "red"), horiz = F, text.col = "black",
cex = 1, pt.cex = .5, inset = c(0.02, 0.02))
# -------------------------------------- #
# Plot output gap and real rate gap
# -------------------------------------- #
outputgap.ts.sp <- ts(outputgap.sp, frequency = 4, start = c(1978,1), end = c(2018, 1))
realrategap.ts.sp <- ts(realrategap.sp, frequency = 4, start = c(1978,1), end = c(2018, 1))
plot.ts(outputgap.ts.sp, ylim = c(-20, 15), xlab=" ", ylab=" ", axes = F, col="blue")
lines(realrategap.ts.sp, lty = 2, col = "red")
abline(h = 0, lty = 2)
legend("topright", legend = c("Output Gap", "Real Rate Gap"),
bty = "n", lty = c(1,2), col = c("blue", "red"), horiz = F, text.col = "black",
cex = 1, pt.cex = .5, inset = c(0.02, 0.02))
title(main = "Output Gap and Real Rate Gap", line = 0.5, font.main = 3)
box()
axis(side = 4)
axis(side = 1)
How would one specify the years on the x-axis from 1975 to 2020 with jumps of 5 years?
Furthermore, (off-topic) I need two plots next to each other, but I feel that par(mfrow = c(2,2)) is not the correct statement. However, changing it into par(mfrow = c(1,2)) creates abnormal large figures.
Thanks!
The OP has requested to specify the years on the x-axis from 1975 to 2020 with jumps of 5 years.
This can be achieved by
axis(1, at = seq(1975L, 2020L, by = 5L))
However, the result may depend on the mfrow parameter. Here is a a dummy example using par(mfrow = c(2, 2)):
Note that the x-axis of the left graph was created by axis(1) while the x-axis of the right graph was created by axis(1, at = seq(1975L, 2020L, by = 5L)). Also note the large white space below the two graphs.
With par(mfrow = c(1, 2)) the result becomes
Here, the right graph shows unlabeled ("minor") tick marks. This is explained in the mfrow section of ?par: In a layout with exactly two rows and columns the base value of "cex" is reduced by a factor of 0.83. So, font size is reduzed by 17% per cent which allows to label all tick marks without overplotting.

Add Min/Max Values as Horizontal Lines in R Plot

I have made a line chart in R and now I want to add a two more lines of min and max values that are already exist in seperate column in same csv file. Here is my code that i used
plot(MedTemp$Loggers.distance, MedTemp$Temperature..C...2017., xaxt = "n", xlab = "",ylab = "", main = "Median Temperature 2017", col.main = "darkred", col = "blue", pch = 19, ylim = c(-5,25), fill = "blue", type = "o")
axis(1, at = c(0, 4698.91, 5424.74, 8731.54, 10103.81, 14361.29 ), cex.axis = 0.55, las = 2)
lines(MedTemp$Loggers.distance[order(MedTemp$Loggers.distance)], MedTemp$Temperature..C...2017.[order(MedTemp$Loggers.distance)], xlim = range(MedTemp$Loggers.distance), ylim = range(MedTemp$Temperature..C...2017.), pch = 16, col = "firebrick", lwd = 1.5)
text(MedTemp$Temperature..C...2017.~ MedTemp$Loggers.distance, labels = c(" ","Orchar\nHill","Roland\nRoad","Gilligan\nRoad","Wetaskiwin"," "), cex = 0.5, font = 2, pos = 1, srt = 0)
text(MedTemp$Temperature..C...2017.~ MedTemp$Loggers.distance, labels = c("Rice\nRoad"," "," "," "," "," "), cex = 0.5, font = 2, pos = 1, srt = 0)
text(MedTemp$Temperature..C...2017.~ MedTemp$Loggers.distance, labels = c(" "," "," "," "," ","Decew\nRoad"), cex = 0.5, font = 2, pos = 1, srt = 0)
mtext(1, text = "Thermal Loggers Chainage Distance(m)", line = 3, cex = 0.9)
mtext(2, text = "Temperature (C)", line = 3, cex = 0.9)
Here is my data:
Here is my chart:
Any help would be appreciated.
The command you're looking for is abline. something along the lines of
abline(h = c(min_value, max_value))
You can add similar instructions for color, linetype, linewidth to the function as did with other plot functions.

How to remove the zero labels in Histogram plot in R?

Any tips to remove the zero labels in between the histogram bars?
hist(links$Survey_Duration, breaks = seq(0,50,5), main = "Survey Duration",
labels = TRUE, border = "black",
xlab = "Survey", ylim = c(0, 15), col = "gray", las = 1, xaxt='n')
axis(side=1, at=seq(0,50,5), labels=seq(0,50,5))
abline(v = mean(links$Survey_Duration), col = "royalblue", lwd = 1.5)
abline(v = median(links$Survey_Duration), col = "red", lwd = 1.5)
legend(x = "topright", c("Mean", "Median"), col = c("royalblue","red"),
lwd = c(1.5,1.5))
How about this?
# modify data so there's zero in one of the bins
mtcars$mpg <- ifelse(mtcars$mpg >= 25 & mtcars$mpg <= 30, NA, mtcars$mpg)
# save plot parameters
h <- hist(mtcars$mpg, plot = FALSE)
# produce plot
plot(h, ylim = c(0, 14))
# add labels manually, recoding zeros to nothing
text(h$mids, h$counts + 1, ifelse(h$counts == 0, "", h$counts))
A slightly different answer using the labeling in hist instead of adding text afterwards.
You do not provide your data, so I will use some data that is handy to illustrate.
The labels argument can specify the individual labels
H1 = hist(iris$Sepal.Length, breaks = 3:8, plot=FALSE)
BarLabels = H1$counts
BarLabels[BarLabels == 0] = ""
hist(iris$Sepal.Length, breaks = 3:8, labels = BarLabels)
Thanks #Daniel Anderson, it Ok now (Thumbs Up)
links$Survey_Duration <- ifelse(links$Survey_Duration > 15 &
links$Survey_Duration <= 25,
NA,
links$Survey_Duration)
h <- hist(links$Survey_Duration, breaks = seq(0,50,5), plot = FALSE)
plot(h, ylim = c(0, 14), main = "Survey Duration", xlab = "Time", col = "gray", las = 1)
text(h$mids, h$counts + 1, ifelse(h$counts == 0, "", h$counts))
axis(side=1, at=seq(0,50,5), labels=seq(0,50,5))
abline(v = mean(links$Survey_Duration), col = "royalblue", lwd = 1.5)
abline(v = median(links$Survey_Duration), col = "red", lwd = 1.5)
legend(x = "topright",
c("Mean", "Median"),
col = c("royalblue","red"),
lwd = c(1.5,1.5))

Resources