Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make graph color depend on two criteria in ggplot2?

Tags:

r

ggplot2

Suppose I have a data frame as defined below:

x <- seq(0, 10, by = 0.1)
y1 <- sin(x)
y2 <- cos(x)
y3 <- cos(x + pi / 4)
y4 <- sin(x + pi / 4)
df1 <- data.frame(x, y = y1, Type = as.factor("sin"), Method = as.factor("method1"))
df2 <- data.frame(x, y = y2, Type = as.factor("cos"), Method = as.factor("method1"))
df3 <- data.frame(x, y = y3, Type = as.factor("cos"), Method = as.factor("method2"))
df4 <- data.frame(x, y = y4, Type = as.factor("sin"), Method = as.factor("method2"))

df.merged <- rbind(df1, df2, df3, df4)

So I want to plot the merged data frame and see what is the influence of Type and Method criteria on data. I can of course use colours for Type and line type for Method:

ggplot(df.merged, aes(x, y, colour = Type, linetype = Method)) + geom_line()

But when two curves with the same Type and different Methods are close to each other, it can sometime be hard to distinguish them.

How can I use only colours to distinguish both Type and Method criteria?

like image 474
Ben Avatar asked May 10 '16 09:05

Ben


People also ask

How do I assign default colors to a ggplot2 plot based on species?

The following code shows how to assign default colors to the points in a ggplot2 plot based on the factor variable Species: Since we didn’t specify a color scale or a list of custom colors, ggplot2 simply assigned a list of default red, green, and blue colors to the points.

How to create a simple bar plot in your using Ggplot2?

First, you need to install the ggplot2 package if it is not previously installed in R Studio. For creating a simple bar plot we will use the function geom_bar ( ). stat : Set the stat parameter to identify the mode. fill : Represents color inside the bars. color : Represents color of outlines of the bars.

What is categorical data in ggplot?

When working with categorical data, each distinct level in your dataset will be mapped to a distinct color in your graph. With categorical data, the goal is to have highly differentiated colors so that you can easily identify data points from each category. There are built-in functions within ggplot to generate categorical color palettes.

Can ggplot2 barcharts have manually specified colors?

Figure 4: ggplot2 Barchart with Manually Specified Colors – Group Colors as in Figure 3. Figures 3 and 4 are showing the output: Two barcharts with different groups, but the same color for groups that appear in both plots. I have recently published a video on my YouTube channel, which shows the R programming syntax of this post.


1 Answers

You could do

ggplot(df.merged, 
       aes(x, y, colour = interaction(Type, Method))) + 
  geom_line()

enter image description here

like image 87
lukeA Avatar answered Oct 22 '22 13:10

lukeA