Mismatch in legend/color in R plot - r

I created several plots in R. Occasionally, the program does not match the color of the variables in the plot to the variable colors in the legend. In the attached file (Unfortunately, I can't yet attach images b/c of reputation), the first 2 graphs are assigned a black/red color scheme. But, the third chart automatically uses a green/black and keeps the legend with black/red. I cannot understand why this happens.
How can I prevent this from happening?
I know it's possible to assign color, but I am struggling to find a clear way to do this.
Code:
plot(rank, abundance, pch=16, col=type, cex=0.8)
legend(60,50,unique(type),col=1:length(type),pch=16)
plot(rank, abundance, pch=16, col=Origin, cex=0.8)
legend(60,50,unique(Origin),col=1:length(Origin),pch=16)
Below is where color pattern won't match
plot(rank, abundance, pch=16, col=Lifecycle, cex=0.8)
legend(60,50,unique(Lifecycle),col=1:length(Lifecycle),pch=16)
data frame looks like this:
Plant rank abundance Lifecycle Origin type
X 1 23 Perennial Native Weedy
Y 2 10 Annual Exotic Ornamental
Z 3 9 Perennial Native Ornamental

First, I create some fake data.
df <- data.frame(rank = 1:10, abundance = runif(10,10,100),
Lifecycle = sample(c('Perennial', 'Annual'), 10, replace=TRUE))
Then I explicitly say what colors I want my points to be.
cols=c('dodgerblue', 'plum')
Then I plot, using the factor df$Lifecycle to color points.
plot(df$rank, df$abundance, col = cols[df$Lifecycle], pch=16)
When the factor df$Lifecycle is used above, it converts it to a numeric reference to cols, such that it sorts the values alphabetically. Therefore, in the legend, we just need to sort the unique df$Lifecycle values, and then hand it our color vector (cols).
legend(5, 40, sort(unique(df$Lifecycle)), col=cols, pch=16, bty='n')
Hopefully this helps.

Related

Issues with colour in plots [duplicate]

I am making a scatter plot of two variables and would like to colour the points by a factor variable. Here is some reproducible code:
data <- iris
plot(data$Sepal.Length, data$Sepal.Width, col=data$Species)
This is all well and good but how do I know what factor has been coloured what colour??
data<-iris
plot(data$Sepal.Length, data$Sepal.Width, col=data$Species)
legend(7,4.3,unique(data$Species),col=1:length(data$Species),pch=1)
should do it for you. But I prefer ggplot2 and would suggest that for better graphics in R.
The command palette tells you the colours and their order when col = somefactor. It can also be used to set the colours as well.
palette()
[1] "black" "red" "green3" "blue" "cyan" "magenta" "yellow" "gray"
In order to see that in your graph you could use a legend.
legend('topright', legend = levels(iris$Species), col = 1:3, cex = 0.8, pch = 1)
You'll notice that I only specified the new colours with 3 numbers. This will work like using a factor. I could have used the factor originally used to colour the points as well. This would make everything logically flow together... but I just wanted to show you can use a variety of things.
You could also be specific about the colours. Try ?rainbow for starters and go from there. You can specify your own or have R do it for you. As long as you use the same method for each you're OK.
Like Maiasaura, I prefer ggplot2. The transparent reference manual is one of the reasons.
However, this is one quick way to get it done.
require(ggplot2)
data(diamonds)
qplot(carat, price, data = diamonds, colour = color)
# example taken from Hadley's ggplot2 book
And cause someone famous said, plot related posts are not complete without the plot, here's the result:
Here's a couple of references:
qplot.R example,
note basically this uses the same diamond dataset I use, but crops the data before to get better performance.
http://ggplot2.org/book/
the manual: http://docs.ggplot2.org/current/
There are two ways that I know of to color plot points by factor and then also have a corresponding legend automatically generated. I'll give examples of both:
Using ggplot2 (generally easier)
Using R's built in plotting functionality in combination with the colorRampPallete function (trickier, but many people prefer/need R's built-in plotting facilities)
For both examples, I will use the ggplot2 diamonds dataset. We'll be using the numeric columns diamond$carat and diamond$price, and the factor/categorical column diamond$color. You can load the dataset with the following code if you have ggplot2 installed:
library(ggplot2)
data(diamonds)
Using ggplot2 and qplot
It's a one liner. Key item here is to give qplot the factor you want to color by as the color argument. qplot will make a legend for you by default.
qplot(
x = carat,
y = price,
data = diamonds,
color = diamonds$color # color by factor color (I know, confusing)
)
Your output should look like this:
Using R's built in plot functionality
Using R's built in plot functionality to get a plot colored by a factor and an associated legend is a 4-step process, and it's a little more technical than using ggplot2.
First, we will make a colorRampPallete function. colorRampPallete() returns a new function that will generate a list of colors. In the snippet below, calling color_pallet_function(5) would return a list of 5 colors on a scale from red to orange to blue:
color_pallete_function <- colorRampPalette(
colors = c("red", "orange", "blue"),
space = "Lab" # Option used when colors do not represent a quantitative scale
)
Second, we need to make a list of colors, with exactly one color per diamond color. This is the mapping we will use both to assign colors to individual plot points, and to create our legend.
num_colors <- nlevels(diamonds$color)
diamond_color_colors <- color_pallet_function(num_colors)
Third, we create our plot. This is done just like any other plot you've likely done, except we refer to the list of colors we made as our col argument. As long as we always use this same list, our mapping between colors and diamond$colors will be consistent across our R script.
plot(
x = diamonds$carat,
y = diamonds$price,
xlab = "Carat",
ylab = "Price",
pch = 20, # solid dots increase the readability of this data plot
col = diamond_color_colors[diamonds$color]
)
Fourth and finally, we add our legend so that someone reading our graph can clearly see the mapping between the plot point colors and the actual diamond colors.
legend(
x ="topleft",
legend = paste("Color", levels(diamonds$color)), # for readability of legend
col = diamond_color_colors,
pch = 19, # same as pch=20, just smaller
cex = .7 # scale the legend to look attractively sized
)
Your output should look like this:
Nifty, right?
The col argument in the plot function assign colors automatically to a vector of integers. If you convert iris$Species to numeric, notice you have a vector of 1,2 and 3s So you can apply this as:
plot(iris$Sepal.Length, iris$Sepal.Width, col=as.numeric(iris$Species))
Suppose you want red, blue and green instead of the default colors, then you can simply adjust it:
plot(iris$Sepal.Length, iris$Sepal.Width, col=c('red', 'blue', 'green')[as.numeric(iris$Species)])
You can probably see how to further modify the code above to get any unique combination of colors.
The lattice library is another good option. Here I've added a legend on the right side and jittered the points because some of them overlapped.
xyplot(Sepal.Width ~ Sepal.Length, group=Species, data=iris,
auto.key=list(space="right"),
jitter.x=TRUE, jitter.y=TRUE)

How to add more points/dots on an existing pairs plot?

par(mfrow=c(1,2))
Trigen <- data.frame(OTriathlon$Gender,OTriathlon$Swim,OTriathlon$Bike,OTriathlon$Run)
colnames(Trigen) <- c("Gender","Swim","Bike","Run")
res <- split(Trigen[,2:4],Trigen$Gender)
pairs(res$Male, pch="M", col = 4)
points(res$Female, pch ="F", col= 2)
Basically, Customize the pairs plot, so where the plot symbol and color of each data point represents
gender.
I did some random things in the code but the issue that I am facing is that I cant add female points to the existing plot. After running the points code it just stays the same doesn't get updated
There is no need to call points sevral times, because you can use the factor directly as a color. Example:
plot(iris[,c(2,3)], col=iris$Species)

Labels/points colored by category with PCA

I'm using prcomp to do PCA analysis in R, I want to plot my PC1 vs PC2 with different color text labels for each of the two categories,
I do the plot with:
plot(pca$x, main = "PC1 Vs PC2", xlim=c(-120,+120), ylim = c(-70,50))
then to draw in all the text with the different colors I've tried:
text(pca$x[,1][1:18], pca$[,1][1:18], labels=rownames(cava), col="green",
adj=c(0.3,-0.5))
text(pca$x[,1][19:35], pca$[,1][19:35], labels=rownames(cava), col="red",
adj=c(0.3,-0.5))
But R seams to plot 2 numbers over each other instead of one, the pcs$x[,1][1:18] plots the correct points I know because if I use that plot the points it works and produces the same plot as plot(pca$x).
It would be great if any could help to plot the labels for the two categories or
even plot the points different color to make it easy to differentiate between the plots easily.
You need to specify your x and y coordinates a bit differently:
text(pca$x[1:18,1], pca$x[1:18,2] ...)
This means take the first 18 rows and the first column (which is PC1) for the x coord, etc.
I'm surprised what you did doesn't throw an error.
If you want the points themselves colored, you can do it this way:
plot(pca$x, main = "PC1 Vs PC2", col = c(rep("green", 18), rep("red", 18)))

Having difficulty with my plots colors and creating a legend

This is probably a basic question. I’ve produced a plot that displays the home ranges for different lemurs. Great! Hard part done. But they are all lime green. How can I choose a different colour for each of my 5 ID's? It seems like is should be simple but I can’t see anything online. Would anyone be able to suggest something?
I’ve pasted my code below
dd <- read.csv(file.choose(), header = T)
xy <- dd[,c("X","Y")]
id <- dd[,"ID"]
hr<- mcp(xy,id,percent=95)
plot(hr,
main="95% Minimum Convex Polygon",
xlab="X Coordinate",
ylab="Y Coordinate")
Once i have 5 separate colors for my 5 ID's (frodo, bilbo, merry, pippin, sam) it would also be great to create a legend displaying the colors and the related ID. I was playing around with the following code
legend('topright', names(hr)[-1] ,
lty=1, col=c('red', 'blue', 'green',' brown'), bty='o', cex=1.5)
But that seems to just display a legend for the x,y coordinates not my ID's displayed in the plot. Can anyone tell me what i'm doing wrong?
Edit: I got it! The function "col=" doesnt work for polygons. Its "colpol=" Thanks for all the help
The hr object has a class of "area" and "data.frame". There is an area method for plot. It has a colpol argument. See ?plot.area when adehabitat is loaded:
plot(hr, colpol=c('red', 'blue', 'green',' brown') )
Originally it was not clear that you wanted to color the 4 (not 5) areas produced. I thought you wanted the points colored by group, which is what this produced.
If you know that ID is already a factor then the factor call is not needed. as.numeric applied to a factor turns it into an integer ranging from 1 to the number of levels, and that is being used as an index into that vector of 5 colors. If you want to see the names all of the 657 colors available, just type colors(). Refer to ?colors for additional links for managing color palettes.
As pointed out, we don't have the data or the mcp function to see what the hr object gets plotted as. If the plot method for that object is not assigning individual colors for the points, then do this instead:
points(xy[,1], xy[,2],
col = c("red", "green", "blue", "orange", "sandybrown")[as.numeric(factor(dd[,"ID"]))]
)
Is this what you are looking for
plot(hr$X,hr$Y,main="95% Minimum Convex Polygon",xlab="X Coordinate",
ylab="Y Coordinate",
col = rainbow(length(hr$ID))[rank(hr$ID)],
pch=c(1:25)[as.numeric(factor(hr$ID))])
legend('topleft', unique(unlist(as.character(factor(hr$ID)))) ,lty=1,
col=rainbow(length(hr$ID))[ unique(unlist(rank(hr$ID)))],
pch=c(1:25)[unique(unlist(as.numeric(factor(hr$ID))))],
bty='o', cex=1.5)

Coloring points instead of lines in interaction.plot (R)I

I want to make an interaction plot in R as in the example
http://www.ling.upenn.edu/~joseff/rstudy/week4.html#interactionplot
except instead of coloring the lines I want to color the points by some attribute other than the number. The desired functionality would look like
blood_pressure = ... # this will be the x-axis
age_bucket = ... # this will be the interaction-level
gender = ... # color boys blue, girls red
stroke_rate = ... # y-axis
interaction.plot(blood_pressure, age_bucket, stroke_rate, col=gender, type="b"...
Except color=gender actually does what I want
The problem is that interaction.plot actually relies on tapply() to compute aggregated summary measures (mean or median). As interaction.plot just calls matplot, you can use the latter directly if you like, or summarize your data with plyr and plot the results with ggplot2 (more flexible).
# consider the 64x4 dataset OrchardSprays and create a fake
# two-levels factor, say grp, which is in correspondence to rowpos odd/even values
grp <- gl(2, 1, 8, labels=letters[1:2])
# the following won't work (due to color recycling)
with(OrchardSprays,
interaction.plot(treatment, rowpos, decrease,
type="b", pch=19, lty=1, col=as.numeric(colpos), legend=F))
# what is used to draw the 8 lines is computed from
with(OrchardSprays,
tapply(decrease, list(treatment=treatment, rowpos=rowpos), mean))
# the following will work, though
with(OrchardSprays,
interaction.plot(treatment, rowpos, decrease,
type="b", pch=19, lty=1, col=as.numeric(grp), legend=F))
In short, assuming you can find an adequate mapping between gender and your trace factor (age_bucket), you need to construct a vector of colors of size nlevels(age_bucket).

Resources