How can I round up years on axis, I applied as.integer()
function, but it does not work. Usually, I use scale_x_continuous(breaks=2015,2022,2))
in case of ggplot, but now I need something same for ggplotly/plotly
Asked
Active
Viewed 168 times
-1
-
2How about you round the values in your dataFrame, upstream? Maybe a new variable YearRound0 so you keep all information. – Yacine Hajji Jul 11 '22 at 08:07
1 Answers
2
You need to format the date column as date. Assuming you only have the year in your data frame, you can just set it to 1st Jan of each year, e.g.:
# Generate some data
dat <- data.frame(
val = 0:10,
Year = 2010:2020
)
# Get year as date
dat$year_date <- as.Date(
format(
as.Date(
as.character(dat$Year), format = "%Y"
),
"%Y-01-01"
)
)
head(dat, 2)
# val Year year_date
# 1 0 2010 2010-01-01
# 2 1 2011 2011-01-01
Now you can create the plot using scale_x_date()
:
p <- ggplot(dat, aes(year_date, val)) +
geom_point() +
scale_x_date(date_breaks = "1 year", date_labels = "%Y")
ggplotly(p)

SamR
- 8,826
- 3
- 11
- 33