plot(iris$Sepal.Length, iris$Sepal.Width, col = iris$Species)
I know that I can use the legend() function to manually set my legend. However, I have no idea which color was assigned to the different species in my data? Is there an automatic way to get plot() to add a legend?
As #rawr says, palette() determines the colour sequence used. If you use integers to specify colours, it will also look at palette(). Thus
with(iris,plot(Sepal.Length, Sepal.Width, col = Species))
legend("topright",legend=levels(iris$Species),col=1:3, pch=1)
works nicely.
Base R doesn't have an auto-legend facility: the ggplot2 package does.
library(ggplot2)
ggplot(iris,aes(Sepal.Length,Sepal.Width,colour=Species))+geom_point()
gives you a plot with an automatic legend (use theme_set(theme_bw()) if you don't like the grey background).
The built-in lattice package can also do automatic legends:
library(lattice)
xyplot(Sepal.Width~Sepal.Length,group=Species,data=iris,auto.key=TRUE)
Related
I created a plot using ggplot() and turned off linetype part of the legend using "+ guides(linetype=False)".
However, when I use the ggplotly() function it completely overrides this and still displays the linetype in the legend. My thought was I need to remove that part of the legend for the generated plotly object, but I wasn't sure how to just remove the linetype within the plotly object (p object below). I do want to keep the color legend.
An example dataset to be plotted:
library("ggplot2")
library("plotly")
dataset = read.csv("file_loc")
g = ggplot(data=dataset) +
geom_line(x=dataset$Time,
y=dataset$Values,
group=dataset$group,
linetype=dataset$group,
color=dataset$Othervalue) +
# Doesn't work when using ggplotly function
guides(linetype=FALSE)
p = ggplotly(g)
Note: I am using R version 3.6.0, ggplot2 3.3.5, plotly 4.9.4.1
I found that if I turn off the legend for p or p=layout(p,showlegend=FALSE) it turns off just the plotly legends but keeps the ggplot legends previously hidden or kept.
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)
I am having to use base R and I am only really familiar with ggplot2. I have told R to colour my plot by site, which it has done... but unlike ggplot2 it doesn't automatically give me a legend to tell me which colour it has assigned to which site. Is there either a way to tell R to plot a site in a specific colour or a way to make it create a legend. I tried creating a legend but it seemed I had to input exactly what colour, shape etc should be on the legend which defeats the point.
Thanks.
plot(mod1.xval, xval=TRUE, resid=TRUE, xlab="Observed elevation (m AHD)", ylab= "Inferred elevation (m AHD)",npls=2,col=spec$Site)
Here is an example with the iris data set.
Species would be your Site. You define the color for Species and then build the legend, in which the colors are made with unique(iris$Species)) .
plot(Sepal.Length~ Sepal.Width, iris, col=Species, pch=16)
legend('topleft', col=unique(iris$Species), legend=levels(iris$Species), pch =15)
I know it could be a simple question, but I'm really struggling..
Using the iris dataset as an example, I can use the following code to perform a plot with different colors depending on the different species:
plot(iris$Sepal.Length, iris$Sepal.Width, col=iris$Species)
legend('topright', legend=c("setosa", "virginica", "versicolor"))
but actually I'm not able to add the same colors used in the plot call in the legend.
Furthermore, the dataset I'm using has several unique values. Is there a way to add the colors without specifying them manually?
ggplot adds automatically the legend according to the color used in the aes option, but I need to do the same thing with the plot package.
Is there a simple solution?
Thanks
Your plot call uses the default colors corresponding to the values of iris$Species (i.e. 1,2,3, remember it's a factor, see the output of as.numeric(iris$Species)!)
For only a few classes the easy solution is to do something like:
cols <- c("darkgreen", "darkblue", "orange")
plot(iris$Sepal.Length, iris$Sepal.Width, col=cols[iris$Species], pch=20)
legend('topright', legend=levels(iris$Species),
col= cols, pch=20)
A more general solution is to use a palette of colours, using functions such as heat.colors, gray.colors or rainbow.colors, for instance
cols <- heat.colors(5) // 5 is the number of colors in the palette
More fancy palettes are found in the RColorBrewer package.
Also, the colorRampPalette function allows you to blend those palettes to get a more smooth result. For instance:
library(RColorBrewer)
colorRampPalette(brewer.pal(9,"Blues"))(100)
you can try this
plot(Sepal.Width~Sepal.Length, data=iris, col=Species)
legend('topright', legend=levels(iris$Species), col=1:3, pch=1)
I'm relatively new to ggplot2, and I'm having trouble adding appropriate labels to my contours. I would love to be able to add the labels without the directlabels package, but I haven't found a way to, so if you know of a way to customize labels without directlabels, I would love to here it.
Using the classic volcano example, I can add labels to the default contour plot using the directlabels packet in the following way:
library(plyr)
library(ggplot2)
library(directlabels)
library(reshape)
volcano<-melt(volcano)
v<-ggplot(volcano, aes(x,y,z=z))
e<-v + stat_contour(aes(colour=..level..))
direct.label(e)
In the above example, the labels are added appropriately, but things become more complicated if I try to specify my own break points for the contours:
e<-v + stat_contour(aes(breaks=c(160, 170, 180), colour=..level..))
direct.label(e)
Now, the contours are specified by the breaks I have provided, but labels still appear for all of the default contours. How do I only plot only labels for the graphed contours?
A related issue, how would I plot labels for contour levels not included in the default? Say a break of 165:
e<-v + stat_contour(aes(breaks=c(165), colour=..level..))
direct.label(e)
Thanks for any help!
The current development version (directlabels_2013.6.15 with ggplot2_0.9.3.1) should fix your problem (as the author of the directlabels package explained to me). You can install it with:
install.packages("directlabels", repos="http://r-forge.r-project.org")
And then:
library(plyr)
library(ggplot2)
library(directlabels)
library(reshape)
volcano<-melt(volcano)
v<-ggplot(volcano, aes(X1,X2,z=value))
e<-v + stat_contour(aes(colour=..level..), breaks=c(165))
direct.label(e)
I noted several other limitations with simple workarounds:
the first ggplot call must contain the z aesthetic
this works only with the stat_contour (and not with the geom_contour)
the colour aesthetic must be defined in the stat_contour call and set to ..level..
Finally, if you want to control the label and contour line colours (black labels and blue contour lines for instance), you can achieved this as follow:
e<-v + stat_contour(aes(colour=..level..), colour = "blue", breaks=c(165))
e<-e + scale_colour_continuous(low = "#FF0000", high = "#FF0000")
direct.label(e)