I'm trying to create a simple double line graph with a dataset I made. Here's the data:
date <- c("2021-04-06","2021-04-10", "2021-04-14", "2021-04-18")
as.Date(date)
graded <- c(3408, 3572, 3647, 3864)
psa10 <- c(2099, 2130, 2147, 2193)
graded_marvel <- data.frame(date, graded, psa10)
graded_marvel
And here's what I did to try and graph this
library("ggplot2")
graph <- ggplot(graded_marvel, aes(date)) +
geom_line(aes(y = graded), color = "darkred") +
geom_line(aes(y = psa10), color = "blue")
print(graph)
All I get is an empty graph that has the correct values on the axes, but the graph just comes up empty. Not sure what to do. Any help is appreciated!
This happens because your date
variable is not a date, so ggplot2 interprets is as a character and assigns a discrete x scale. This auto-groups your data based on the x-axis value, so every 'group' only has one observations, with which you cannot draw a line. The way to fix this is to convert your date to a proper Date
class.
library(ggplot2)
date <- c("2021-04-06","2021-04-10", "2021-04-14", "2021-04-18")
graded <- c(3408, 3572, 3647, 3864)
psa10 <- c(2099, 2130, 2147, 2193)
graded_marvel <- data.frame(date, graded, psa10)
ggplot(graded_marvel, aes(as.Date(date))) +
geom_line(aes(y = graded), color = "darkred") +
geom_line(aes(y = psa10), color = "blue")
Created on 2021-04-19 by the reprex package (v1.0.0)
First get long format with pivot_longer
. Then plot with ggplot2
.
library("ggplot2")
ggplot(df, aes(x=factor(date), y = values, group = names)) +
geom_point(aes(color=names)) +
geom_line(aes(linetype=names, color=names)) +
scale_colour_manual(values=c("darkred", "blue"))
data:
df <- graded_marvel %>%
pivot_longer(
cols = -date,
names_to = "names",
values_to = "values"
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.