Changing the colour of graph in ggplot - r

In the below graph, I want to change the colour of the left graph as red, and the right graph as blue. How can I simply do that using the below command? Many thanks in advance.
normgraph <- ggplot (data=data1, aes (x=x1)) +
geom_density() +
geom_density(data=data2, aes(x=x2)) +
labs(title="The variation of grain weight") +
labs (y="Frequency(%)") +
labs (x="Grain weight (mg)") +
lims(x=c(50,70))

Since data is not provided, I will use iris to illustrate how to do this. Note that code is similar to yours; I just haven't included any further customizations relevant for your plot (as they depend on your dataset).
library(ggplot2)
ggplot(data = iris, aes(x = Sepal.Length)) +
geom_density(color = "blue") +
geom_density(data = iris, aes(x = Sepal.Width), color = "red")
Created on 2019-02-13 by the reprex package (v0.2.1)

Related

r ggplot: multiple geoms and scales (which scale overides which geom?)

I intended to color lines in pink, and points in yellow. I don't want to use colour argument in respective geom(), I want to use scale to change colour.
p3 <- ggplot(dfcc,aes(x = yr, y = mean)) +
geom_line(aes(color = '')) +
geom_point(aes(color = ''))
p3 + scale_colour_manual(values =c('pink', 'yellow'))
This gives this plot, both lines and points are not in the right colours.
Hence, I have two questions
can I use "scale_colour_manual" to change the line and point colors in one go?
if having multiple geoms and multiple scales, how does the system know which scale applies to which geom?
Any help and explanation would be much appreciated!
Use package ggnewscale.
set.seed(2022)
df1 <- data.frame(x = 1:20, y = cumsum(rnorm(20, 2)))
library(ggplot2)
ggplot(df1, aes(x, y)) +
geom_line(color = "pink", linewidth = 2) +
ggnewscale::new_scale_color() +
geom_point(color = "yellow", size = 3) +
theme_classic()
Created on 2022-12-25 with reprex v2.0.2

Choosing the color of only one of the plotted elements

I'm using ggplot to plot a set of values in R and want to colour them according to their sensor name. However, I'd like to change the colour of one of the sensors (not all of them as they are many). Do you have any suggestions?
I'm going to use the following command:
ggplot(molted1, aes( Duration,value,group=test ))+
geom_point(aes(color=sensor))+
facet_grid(~test,scales = "free") +
theme_bw()+
scale_x_continuous(breaks=pretty_breaks(n=3))+
theme(legend.position = "none",axis.title=element_text(size=11))+labs(x="",y="Temperature \n(°C)")
One option is to map the color to the logical test of sensor == selected and then supply the background and highlight colors to scale_color_manual().
If you want to more than one sensor to get highlighted and show different colors for just those ones, you may want to take a look at the {gghighlight} package which does this nicely.
library(tidyverse)
mtcars %>%
ggplot(aes(disp, mpg)) +
geom_point(aes(color = carb == 4), size = 4) +
scale_color_manual(values = c("grey50", "red")) +
facet_grid(~gear)
Created on 2022-04-08 by the reprex package (v2.0.1)

How do I get my legend dots blue and red instead that both are red?

I am trying to get a red and a blue dot in my legend, this is not the data that I am using but a reproducible example,
The graph exits of two dataset, example is one of them and example1.
here is my code:
if (!require("pacman")) install.packages("pacman")
pacman::p_load_gh("trinker/wakefield")
example <- r_data_frame(
n = 100,
id,
iq,
age,
height
)
example1 <- r_data_frame(
n = 100,
id,
iq,
age,
height)
library(ggplot2)
color_names <- c("example", "example1")
color_values <- c("blue", "red")
names(color_values) <- color_names
ggplot() +
#These points need to be blue and in the legend as well.
geom_point(data=example, aes(x=ID, y=Height,
fill ="example"),
colour="darkblue", size=1) +
#These points need to be red and red in the legend
geom_point(data=example1, aes(x=ID, y=Height,
fill ="example1"), colour = "red"
, size=1) +
# plot configuration scales, theme, etc...
scale_colour_manual(values = color_values) +
scale_fill_manual(values = color_values) +
theme_bw()
The main issue here is that you are setting the colour using the color names for the points but also overwriting these settings with scale_colour_manual and scale_fill_manual.
As you are using geom_point() it is not necessary to change the fill unless you use a different point type.
I would suggest labelling the colours in aes() with the examples (not just fill). My solution removes all excess scales I can add these back in if you need them in your actual implementation (not the reprex as it is unneccessary here).
I have additionally modified the colour_values variable to contain the name and the colour in one line (rather than your implementation).
if (!require("pacman")) install.packages("pacman")
pacman::p_load_gh("trinker/wakefield")
example <- r_data_frame(
n = 100,
id,
iq,
age,
height
)
#> Warning: `tbl_df()` was deprecated in dplyr 1.0.0.
#> Please use `tibble::as_tibble()` instead.
example1 <- r_data_frame(
n = 100,
id,
iq,
age,
height)
library(ggplot2)
color_values <- c("example" = "darkblue", "example1" = "red")
ggplot() +
#These points need to be blue and in the legend as well.
geom_point(data=example, aes(x=ID, y=Height,color = "example"), size=1) +
#These points need to be red and red in the legend
geom_point(data=example1, aes(x=ID, y=Height,
color = "example1"), size=1) +
# plot configuration scales, theme, etc...
scale_colour_manual(name = "colour", values = color_values) +
theme_bw()
Created on 2021-04-07 by the reprex package (v2.0.0)
Taking Joel Kandiah's answer a step further (+1), I'd use a more natural way for ggplot2 to make use of their fantastic aesthetics - use a long format if your data frames contain the same variables. Just bind them together.
Avoids headaches and hard coding, and also reduces your code.
library(wakefield)
library(tidyverse)
example <- r_data_frame(n = 100, id, iq, age, height)
#> Warning: `tbl_df()` was deprecated in dplyr 1.0.0.
#> Please use `tibble::as_tibble()` instead.
example1 <- r_data_frame(n = 100, id, iq, age, height)
color_values <- c(example = "darkblue", example1 = "red")
bind_rows(mget(ls(pattern = "^example")), .id = "example") %>%
ggplot() +
geom_point(aes(x=ID, y=Height,color = example), size=1) +
scale_colour_manual(name = "colour", values = color_values) +
theme_bw()
Created on 2021-04-07 by the reprex package (v1.0.0)

Subdividing jitter points in ggplot

I'm having difficulty getting geom_jitter to separate my data points by a third variable (phase).
I'd like for each bar in this 2x2 graph to have its own set of jittered data points for each phase condition.
Right now the points are grouped between the two phase bars (sorry couldn't upload the image -- don't have my 10 posts yet).
I know I'm missing something in the geom_jitter aes, but not sure what it is -- fill=phase is not doing the trick.
ggplot(datalong, aes(grp, score)) +
geom_bar(stat = "summary", fun.y = "mean", aes(fill=phase), position = "dodge", alpha = .5) +
geom_jitter(inherit.aes = FALSE, aes(grp, score, fill=phase), position = position_jitter(0.2))
The default shape for points does not take the fill aesthetic
Compare
library(ggplot2)
ggplot(mtcars, aes(mpg, disp, fill = gear)) +
geom_jitter()
ggplot(mtcars, aes(mpg, disp, color = gear)) +
geom_jitter()
ggplot(mtcars, aes(mpg, disp, fill = gear)) +
geom_jitter(shape = 21)
Created on 2020-07-09 by the reprex package (v0.3.0)
Found a solution using:
geom_point(position=position_jitterdodge())
This seems to jitter and dodge to separate the points.

Single Integer Color Input: What Color Space? How to enter Greyscale?

I am creating a set of maps in R and am looking to color my points, but I am unsure what color space I inputed. My code is as follows:
library("ggplot2")
library("sf")
library("rnaturalearth")
library("rnaturalearthdata")
library("maps")
world <- ne_countries(scale = "medium", returnclass = "sf")
states <- st_as_sf(map("state", plot = FALSE, fill = TRUE))
states <- cbind(states, st_coordinates(st_centroid(states)))
ggplot(data = world) +
geom_sf() +
geom_sf(data = states, fill = "cornsilk") +
geom_path(data = observationsByReceiver, aes(x = Longitude, y = Latitude)) +
geom_point(data = observationsByReceiver, aes(x = Longitude, y = Latitude), size = 2, color = 2)
There are a couple more lines, but they are purely stylistic.
My questions is what color space is it when I write "color = 2"? I'm looking to create a grey scale gradient for my points and thought this might be the way to input gray scale, but it comes out as red. So what space am I in? And how do I input grey scale?
Thank you.
I'll illustrate with the iris dataset, as I don't have the packages you state and I'm not looking to download these at the moment.
In general there are 2 scenarios: 1 for categorical variables and 1 for continuous variables.
Categorical
The simplest case is if you want all points in the same layer to have the same colour. You can then simply add the colour as argument to the layer.
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.0.2
ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
geom_point(color = "blue")
A second case occurs when you want to map your aesthetic to a (colour) scale, which is more common if you want to have finer control over the looks of your point. By default it sort of chooses colours along a rainbow for you.
ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
geom_point(aes(colour = Species))
Lastly, you can control the mapped colour via a scale. For you example, this is a greyscale that would fit.
ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
geom_point(aes(colour = Species)) +
scale_colour_brewer(palette = "Greys")
Continuous
Continuous values are most often mapped to a scale. By default it chooses a blue palette for you.
ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
geom_point(aes(color = Petal.Width))
But again, you can control the gradient via the scale too.
ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
geom_point(aes(color = Petal.Width)) +
scale_colour_distiller(palette = "Greys")
As an aside, the same thing applies to fills but they colour different parts of graphical objects.
As for your second question:
Looking into ?palette:
View or manipulate the color palette which is used when col= has a numeric index (etc...)
Interestingly, ggplot2 doesn't change this after setting the palette.
update
ggplot2 maintainer Thomas Lin Pedersen on this issue:
This is ... a known result of using farver for colour conversion.
library(ggplot2)
palette()
#> [1] "black" "#DF536B" "#61D04F" "#2297E6" "#28E2E5" "#CD0BBC" "#F5C710"
#> [8] "gray62"
plot(1:8, col = 1:8, pch = 16)
#change the palette to "Reds"
palette(RColorBrewer::brewer.pal(8, "Reds"))
plot(1:8, col = 1:8, pch = 16)
# ggplot2 does not change, still the original palette ...
# (I guess it does not scope for the palette in the global environment)
ggplot(data.frame(x = 1:8, y = 1), aes(x,y, color = x)) +
geom_point() +
scale_color_identity()

Resources