I want to use geom_segment to make a line intercept the y-axis, the problem I am experiencing becomes readily apparent. Starting off with sample data:
dat <- data.frame(Yaxis = c(100,200,300,400,500,600,700,800), Year = c(2012,2013,2014,2015,2016,2017,2018,2019))
p <- ggplot(data=dat, aes(x=Year)) + geom_line(aes(y=Yaxis))
and adding a geom_segment layer produces:
p + geom_segment(aes(x=0,xend=2012,y=75,yend=100))
my attempts to amend this haven't worked out so far:
p + geom_segment(aes(x=0,xend=2012,y=75,yend=100)) + scale_x_continuous(expand= c(0,0), breaks = c(2012,2013,2014,2015,2016,2017,2018,2019))
For reference, here is a crude drawing of what I intend the graph to look like:
Thanks to #Sathish 's answer, I was able to create the graph I intended using
ggplot(data=dat, aes(x=as.Date(paste(Year,'-01-01', sep=""), "%Y-%m-%d"), y=Yaxis)) +
geom_line() +
geom_segment(aes(
x=as.Date("2011-01-01", "%Y-%m-%d"),
xend=as.Date("2012-01-01", "%Y-%m-%d"),
y=75,
yend=100), color = "red") +
scale_x_date(expand = c(0,0))
Convert Year column to Date class.
library('ggplot2')
ggplot(data=dat, aes(x=as.Date(paste(Year, '-01-01', sep = ""), "%Y-%m-%d"), y=Yaxis)) +
geom_line() +
geom_segment(aes(x=as.Date("2012-01-01", "%Y-%m-%d"),xend=as.Date("2020-01-01", "%Y-%m-%d"),y=75,yend=100), color = "red") +
xlab(label = "Year")
Related
I'm plotting HH:MM:SS on the y-axis against YYYY:MM on the x-axis, but am having issues trying to use scale_y_reverse with scale_y_time together.
sample data below:
library(hms)
library(ggplot2)
df_stack <- data.frame(yr_mn = rep(c("2020-01", "2020-02", "2020-03", "2020-04"),2),
timept_type = c(rep("A",4),rep("B",4)),
timept = as_hms(c("08:00:00", "09:10:00", "11:05:30", "10:45:00", "09:30:10", "10:00:00", "11:25:00", "08:40:00")))
df_stack %>%
ggplot(., aes(x=yr_mn, y=timept, color=timept, fill=timept)) +
geom_point() +
geom_line(aes(group=1))+
facet_wrap(vars(timept_type), scales="free", ncol=2) +
scale_y_time(limits = c(as.POSIXct(as_hms("07:00:00")), as.POSIXct(as_hms("11:30:00")))) +
scale_y_reverse() # this cause the y-axis labels to no longer be in hh:mm:ss format
If I comment out the last line scale_y_reverse() then the graph looks fine, but if I include it, the scale_y_reverse seems to convert the HH:MM:SS into seconds. I have no idea if it's something I'm doing incorrectly or if there's a built-in method within scale_y_time to resolve this. Thanks!
You can omit the scale_y_time and supply functions to scale_y_reverse to generate the labels and the breaks.
df_stack %>%
ggplot(aes(yr_mn, timept, color = timept, fill = timept)) +
geom_point() +
geom_line(aes(group = 1)) +
facet_wrap(vars(timept_type), scales = "free", ncol = 2) +
scale_y_reverse(labels = function(x) as_hms(x),
breaks = seq(as.numeric(as_hms("07:00:00")),
as.numeric(as_hms("11:30:00")),
1800))
Result:
After digging into the code for scale_x_reverse() and scale_x_time(), I've made a simplified version for my data (where x is time, and y is value).
Add a - in front of the variable to be reversed in the aesthetic, and add a reverse label function to scale_x_time(labels = function(x) -x)
ggplot(df, aes(x = -clock, y = points)) +
geom_point() +
scale_x_time(labels = function(x) -x)
xlab("Clock") + ylab("Points")
Reversing the limits may easier and less error-prone.
ggplot(df, aes(x = clock, y = points)) +
geom_point() +
scale_x_time(limits = c(12*60*60,0)) # in seconds
xlab("Clock") + ylab("Points")
I am currently plotting data using the ggpubr package in R (based on ggplot2). When I plot the means of two conditions including standard errors, the y-axis should be limited from 1 to 7, which I indicate using:
p <- ggline(data, x = "condition", y = "measure",
add = c("mean_se"),
ylab = "Measure")
ggpar(y, ylim = c(1, 7), ticks=T, yticks.by = 1)
In the final plot, however, the y-axis shows only values from 1 to 6
I tried to plot the same data using native ggplot2, but the problem persists, once I change the layout.
For ggplot2 I used:
p <- ggplot(data, aes(x=condition, y=measure)) +
geom_line() +
geom_point()+
geom_errorbar(aes(ymin=measure-se, ymax=measure+se), width=.2, position=position_dodge(0.05)) +
ylab("measure") +
xlab("Condition")
p + scale_y_continuous(name="measure", limits=c(1, 7), breaks=c(1:7))
p + theme_classic()
It would be great if someone could help me with this issue.
Edit:
as suggested in the comments, here is the data I am trying to plot using ggplot2:
structure(list(condition = structure(3:4, .Label = c("IC", "SC",
"ILC", "SLC"), class = "factor"), measure = c(4.10233918128655, 3.83040935672515
), se = c(0.235026318386523, 0.216811675834834)), class = "data.frame", row.names = c(NA,
-2L))
I think I got something resembling your plot with correct y-axes with the following code:
ggplot(data, aes(x = condition, y = measure)) +
geom_point() +
geom_errorbar(aes(ymin = measure-se, ymax = measure+se),
width = .2, position = position_dodge(0.05)) +
# Group prevents geom_line interpreting each x-axis point as it's own group
geom_line(aes(group = rep(1, nrow(data)))) +
xlab("Condition") +
# Expand is optional, it prevents padding beyond 1 and 7
scale_y_continuous(name = "measure",
limits = c(1, 7),
breaks = 1:7,
expand = c(0,0)) +
theme_classic()
The solution is much more trivial. You were doing everything right! Except for one clerical error. Here is what was happening:
First, you generate your initial plot, fine.
p <- ggplot(data, aes(x=condition, y=measure)) +
geom_line() + geom_point() +
geom_errorbar(aes(ymin=measure-se, ymax=measure+se),
width=.2, position=position_dodge(0.05)) +
ylab("measure") +
xlab("Condition")
This plot does not have the limits. When you add the limits and display it, the scales are correct:
p + scale_y_continuous(name="measure", limits=c(1, 7), breaks=c(1:7))
However, note that p did not change! You did not store the result of adding the limits to p. Therefore, p is still without the scale_y_continuous. No wonder then that when you type
p + theme_classic()
...the limits are gone. However, if you try
p <- p + scale_y_continuous(name="measure", limits=c(1, 7), breaks=c(1:7))
p + theme_classic()
everything will be correct.
The following are my r code for the scatterplot.
library(tidyverse)
Pop <-c(24039274, 24854892, 25718048, 26624820, 27568436, 28543940, 29550662, 30590487, 31663896, 32771895)
Popu <- data.frame(Year = 2000:2009, lpop = log2(Pop))
ggplot(Popu, aes(Year, lpop)) +
geom_point(size=3, col = "steelblue") +
ylab("Log2 of Population")
My question is, why the x axis reflects 2000.0, 2002.5 and so on? How do I fix this one?
Thank you in advance.
Try this:
Popu <- data.frame(Year = factor(seq(2000,2009,1)), lpop = log2(Pop))
ggplot(Popu, aes(Year, lpop)) +
geom_point(size=3, col = "steelblue") +
ylab("Log2 of Population")
Thi is my data:
x <- c("22-01-16","26-01-16","28-01-16","01-02-16","05-02-16","16-02-16","17-03-16","18-03-16","04-04-16","05-04-16","06-04-16","08-04-16")
y <- c(97.14,75,54.44,70.45,110.56,66.3,178.76,171.90,419.41,424,518.63,242.17)
z <- c("ADCP","ADCP","ADCP","ADCP","ADCP","ADCP","ADCP","ADCP","ADCP","ADCP","ADCP","ADCP")
So I make the dataframe
Datos <- data.frame(x)
Datos$Caudal <- y
Datos$Tipo <- z
Datos$Fecha <- as.Date(Datos$x, "%d-%m-%y")
and plot using ggplot2
Serie_Caudal <-
ggplot(Datos, aes(Fecha, Caudal)) +
geom_line(size=1, colour="red") +
geom_point(shape=23,size=1, colour="blue",fill = "blue") +
scale_x_date(date_breaks = "1 week",labels = date_format("%d/%b"))+
xlab("Fecha") + ylab(bquote('Caudal ('*m^3~s^-1*')')) +
ggtitle("Caudales Diarios (01-06/2016)")
Serie_Caudal
I try to plot a legend but i can´t the way, i try use Melt but my data change in a way i can´t plot. Also try scale_fill_manual but the legend don´t show up. I want to know if there is a way to put a legend manualy.
The legend must show a blue point and ADCP
This shows only a blue dot.
ggplot(aes(Fecha, Caudal, colour = "ADCP"), data = Datos) +
geom_point() +
geom_point(shape=23,size=1,color="blue",fill = "blue") +
scale_color_manual(values = c("ADCP"="blue"),name = "") +
geom_line(color="red", size=1) +
scale_x_date(date_breaks = "1 week",labels = date_format("%d/%b")) +
xlab("Fecha") + ylab(bquote('Caudal ('*m^3~s^-1*')')) +
ggtitle("Caudales Diarios (01-06/2016)")
I am trying to plot the change in a time series for each calendar year using ggplot and I am having problems with the fine control of the x-axis. If I do not use scale="free_x" then I end up with an x-axis that shows several years as well as the year in question, like this:
If I do use scale="free_x" then as one would expect I end up with tick labels for each plot, and that in some cases vary by plot, which I do not want:
I have made various attempts to define the x-axis using scale_x_date etc but without any success. My question is therefore:
Q. How can I control the x-axis breaks and labels on a ggplot facet grid so that the (time series) x-axis is identical for each facet, shows only at the bottom of the panel and is in the form of months formatted 1, 2, 3 etc or as 'Jan','Feb','Mar'?
Code follows:
require(lubridate)
require(ggplot2)
require(plyr)
# generate data
df <- data.frame(date=seq(as.Date("2009/1/1"), by="day", length.out=1115),price=runif(1115, min=100, max=200))
# remove weekend days
df <- df[!(weekdays(as.Date(df$date)) %in% c('Saturday','Sunday')),]
# add some columns for later
df$year <- as.numeric(format(as.Date(df$date), format="%Y"))
df$month <- as.numeric(format(as.Date(df$date), format="%m"))
df$day <- as.numeric(format(as.Date(df$date), format="%d"))
# calculate change in price since the start of the calendar year
df <- ddply(df, .(year), transform, pctchg = ((price/price[1])-1))
p <- ggplot(df, aes(date, pctchg)) +
geom_line( aes(group = 1, colour = pctchg),size=0.75) +
facet_wrap( ~ year, ncol = 2,scale="free_x") +
scale_y_continuous(formatter = "percent") +
opts(legend.position = "none")
print(p)
here is an example:
df <- transform(df, doy = as.Date(paste(2000, month, day, sep="/")))
p <- ggplot(df, aes(doy, pctchg)) +
geom_line( aes(group = 1, colour = pctchg),size=0.75) +
facet_wrap( ~ year, ncol = 2) +
scale_x_date(format = "%b") +
scale_y_continuous(formatter = "percent") +
opts(legend.position = "none")
p
Do you want this one?
The trick is to generate day of year of a same dummy year.
UPDATED
here is an example for the dev version (i.e., ggplot2 0.9)
p <- ggplot(df, aes(doy, pctchg)) +
geom_line( aes(group = 1, colour = pctchg), size=0.75) +
facet_wrap( ~ year, ncol = 2) +
scale_x_date(label = date_format("%b"), breaks = seq(min(df$doy), max(df$doy), "month")) +
scale_y_continuous(label = percent_format()) +
opts(legend.position = "none")
p