问题
I'm plotting a correlation scatter plot, where my data frame has time data and the start year is arbitrary. In this case now I have the following R
code
## Set seed for randomness in dummy data: ##
set.seed(123)
## Create data frame: ##
df.Data <- data.frame(date = seq(as.Date('2019-01-01'), by = '1 day', length.out = 650),
DE = rnorm(650, 2, 1), AT = rnorm(650, 5, 2))
corPearson <- cor.test(x = df.Data$DE, y = df.Data$AT, method = "pearson")
df.Data$year <- format(as.Date(df.Data$date), '%Y')
## PLOT: ##
p <- ggplot(data = df.Data, aes(x = DE, y = AT, group = 1)
) +
geom_point(aes(color = year)) +
geom_smooth(method = "lm", se = FALSE, color = "#007d3c") +
theme_classic() +
theme(legend.position = "none") +
theme(panel.background = element_blank()) +
scale_colour_brewer(palette = 'Greens') +
xlab("PEGAS TTF M1") +
ylab("EEX DEB M1") +
ggtitle("Correlation Scatter Plot (Pearson)") +
theme(plot.title = element_text(hjust = 0.5, face = "bold"))
## Correlation plot converting from ggplot to plotly: #
CorrelationPlot <- plotly::ggplotly(p, tooltip = "text")
which gives the following output:
My problem lies in the color palette. I use the Greens
color palette, which plots data from 2020 in a darker green than data from 2019, which I would like to keep as it is.
Nevertheless, I would like it to start with the darker shades of green, e.g. data from 2020 with the green of the red arrow, data from 2019 with the green of the blue arrow.
How can I do this?
回答1:
You can use scale_color_manual
to set custom colors:
library(ggplot2)
library(RColorBrewer)
## Set seed for randomness in dummy data: ##
set.seed(123)
## Create data frame: ##
df.Data <- data.frame(date = seq(as.Date('2019-01-01'), by = '1 day', length.out = 650),
DE = rnorm(650, 2, 1), AT = rnorm(650, 5, 2))
corPearson <- cor.test(x = df.Data$DE, y = df.Data$AT, method = "pearson")
df.Data$year <- format(as.Date(df.Data$date), '%Y')
## PLOT: ##
p <- ggplot(data = df.Data, aes(x = DE, y = AT, group = 1)
) +
geom_point(aes(color = year)) +
geom_smooth(method = "lm", se = FALSE, color = "#007d3c") +
theme_classic() +
theme(legend.position = "none") +
theme(panel.background = element_blank()) +
scale_color_manual(values=colorRampPalette(brewer.pal(n = 8, name = "Greens")[7:8])( length(unique(df.Data$year)) )) +
xlab(df.Data$DE) +
ylab(df.Data$AT) +
ggtitle("Correlation Scatter Plot (Pearson)") +
theme(plot.title = element_text(hjust = 0.5, face = "bold"))
p
## Correlation plot converting from ggplot to plotly: #
CorrelationPlot <- plotly::ggplotly(p, tooltip = "text")
来源:https://stackoverflow.com/questions/64151267/how-do-you-set-the-color-palette-so-that-it-starts-with-the-darkest-color-where