fill and scale_color in ggplot - r

I am trying to color bars in ggplot but having issues. Can someone explain how to correctly use the fill parameter and the scale_colour parameters?
library(ggplot2)
df<-data.frame(c(80,33,30),c("Too militarized","Just doing their job","Unfairly tarnished by a few"),c("57%","23%","21%"))
colnames(df)<-c("values","names","percentages")
ggplot(df,aes(names,values))+
geom_bar(stat = "identity",position = "dodge",fill=names)+
geom_text(aes(label=percentages), vjust=0)+
ylab("percentage")+
xlab("thought")+
scale_colour_manual(values = rainbow(nrow(df)))
Working barplot example
barplot(c(df$values),names=c("Too militarized","Just doing their job","Unfairly tarnished by a few"),col = rainbow(nrow(df)))

The main issue is that you don't have fill inside a call to aes in geom_bar(). When mapping from data to visuals like colors, it has to be inside aes(). You can fix this by either wrapping fill=names with aes() or by just specifying fill colors directly, instead of using names:
Option 1 (no legend):
ggplot(df, aes(names, values)) +
geom_bar(stat="identity", fill=rainbow(nrow(df))) +
ylab("percentage") +
xlab("thought")
Option 2 (legend, because mapping from data to colors):
ggplot(df, aes(names, values)) +
geom_bar(stat="identity", aes(fill=names)) +
ylab("percentage") +
xlab("thought") +
scale_fill_manual(values=rainbow(nrow(df)))
Note that in both cases you might want to explicitly factor df$names ahead of the call to ggplot in order to get the bars in the order you want.

Related

Legends in ggplot

I am trying plot this data, and the line graph is correct, but I can't make the legend show up. Any thoughts?
ggplot(data, aes(x=time_months, size=I(1))) +geom_line(aes(y=monthly_net_revenue, color=I("blue"))) +
geom_line(aes(y=cumsum(discounted_monthly_net_revenue), color=I("purple"))) +
geom_line(aes(y=monthly_expenses, color=I("red"))) +
geom_line(aes(y=cumsum(monthly_revenue), color=I("green")))
This will probably work for you
ggplot(data, aes(x=time_months, size=I(1))) +
geom_line(aes(y=monthly_net_revenue, color="blue")) +
geom_line(aes(y=cumsum(discounted_monthly_net_revenue), color="purple")) +
geom_line(aes(y=monthly_expenses, color="red")) +
geom_line(aes(y=cumsum(monthly_revenue), color="green")) +
scale_color_identity(guide = "legend")
The scale_color_identity() uses the values you pass to color= directly as the color rather than treating them like a group name. You don't need I() with this method.

How can I use different color or linetype aesthetics in same plot with ggplot?

I'm creating a plot with ggplot that uses colored points, vertical lines, and horizontal lines to display the data. Ideally, I'd like to use two different color or linetype scales for the geom_vline and geom_hline layers, but ggplot discourages/disallows multiple variables mapped to the same aesthetic.
# Create example data
library(tidyverse)
library(lubridate)
set.seed(1234)
example.df <- data_frame(dt = seq(ymd("2016-01-01"), ymd("2016-12-31"), by="1 day"),
value = rnorm(366),
grp = sample(LETTERS[1:3], 366, replace=TRUE))
date.lines <- data_frame(dt = ymd(c("2016-04-01", "2016-10-31")),
dt.label = c("April Fools'", "Halloween"))
value.lines <- data_frame(value = c(-1, 1),
value.label = c("Threshold 1", "Threshold 2"))
If I set linetype aesthetics for both geom_*lines, they get put in the
linetype legend together, which doesn't necessarily make logical sense
ggplot(example.df, aes(x=dt, y=value, colour=grp)) +
geom_hline(data=value.lines, aes(yintercept=value, linetype=value.label)) +
geom_vline(data=date.lines, aes(xintercept=as.numeric(dt), linetype=dt.label)) +
geom_point(size=1) +
scale_x_date() +
theme_minimal()
Alternatively, I could set one of the lines to use a colour aesthetic,
but then that again puts the legend lines in an illogical legend
grouping
ggplot(example.df, aes(x=dt, y=value, colour=grp)) +
geom_hline(data=value.lines, aes(yintercept=value, colour=value.label)) +
geom_vline(data=date.lines, aes(xintercept=as.numeric(dt), linetype=dt.label)) +
geom_point(size=1) +
scale_x_date() +
theme_minimal()
The only partial solution I've found is to use a fill aesthetic instead
of colour in geom_pointand setting shape=21 to use a fillable shape,
but that forces a black border around the points. I can get rid of the
border by manually setting color="white, but then the white border
covers up points. If I set colour=NA, no points are plotted.
ggplot(example.df, aes(x=dt, y=value, fill=grp)) +
geom_hline(data=value.lines, aes(yintercept=value, colour=value.label)) +
geom_vline(data=date.lines, aes(xintercept=as.numeric(dt), linetype=dt.label)) +
geom_point(shape=21, size=2, colour="white") +
scale_x_date() +
theme_minimal()
This might be a case where ggplot's "you can't have two variables mapped
to the same aesthetic" rule can/should be broken, but I can't figure out clean way around it. Using fill with geom_point shows the most promise, but there's no way to remove the point borders.
Any ideas for plotting two different color or linetype aesthetics here?

How to establish specific colors in a barplot in ggplot R? [duplicate]

Does anyone know how to use a pre-defined color palette in ggplot?
I have a vector of colors I would like to use:
rhg_cols <- c("#771C19", "#AA3929", "#E25033", "#F27314", "#F8A31B",
"#E2C59F", "#B6C5CC", "#8E9CA3", "#556670", "#000000")
But when I try to pass it to nothing happened
ggplot(mydata, aes(factor(phone_partner_products)), color = rhg_cols) +
geom_bar()
You must put colour = rhg_cols inside aes(). As far as I can tell, you want to apply gradient to bars (in barplot) with factor variable on the abscissa? Then use fill - try this instead:
ggplot(mydata, aes(factor(phone_partner_products), fill = factor(phone_partner_products))) +
geom_bar() +
scale_fill_manual(values = rhg_cols)
or try to achieve approximate replica with:
ggplot(mydata, aes(factor(phone_partner_products), fill = phone_partner_products))) +
geom_bar() +
scale_fill_gradient(low = "#771C19", high = "#000000")
Notice that in second case a continuous variable is passed to fill aesthetics, therefore scale_fill_gradient is passed afterwards. If you pass a factor to the fill aes, you must stick with scale_fill_manual(values = rhg_cols).
If the colours are a palette, use scale_colour_manual:
ggplot(mydata, aes(factor(phone_partner_products), colour = colour_variable)) +
scale_colour_manual(values = rhg_cols)
First add, the colours to your data set:
mydata$col <- rhg_cols
Then map colour to that column and use scale_colour_identity
ggplot(mydata, aes(factor(phone_partner_products, colour = col))) +
geom_bar() +
scale_colour_identity()
Since the colors you want ARE the values in the color aesthetic, what you really want is the identity scale, in this case scale_fill_identity.
ggplot(mydata, aes(factor(phone_partner_products)), color=rhg_cols) +
geom_bar() +
scale_fill_identity())
Since you didn't supply data, I'm going to use a slightly different example using your color data:
rhg_cols <- c("#771C19","#AA3929","#E25033","#F27314","#F8A31B",
"#E2C59F","#B6C5CC","#8E9CA3","#556670","#000000")
mydata <- sample(rhg_cols, 100, replace = TRUE)
qplot(mydata, fill = mydata) +
scale_fill_identity()
note: I omitted + opts(axis.text.x=theme_text(angle=90)) for clarity in the example.

mix discrete and continuous values to get a fill guide in ggplot2

I want to add a legend for filled rectangles in the background but I already used fill aesthetics for filling the bars of my bar plot.
How can I get the legend or create a matching legend by hand?
df <- data.frame(a=factor(c('a','b','c','c','d','e'), levels=c('a','b','c','d','e')),
x=seq(1,6),
b=factor(c('A','A','A','B','B','B'), levels=c('A','B')),
c=c(1,2,3,4,5,6),
d=rnorm(6))
ggplot(df, aes(x, c, fill=d, group=b)) +
geom_rect(aes(xmin=0.5,xmax=3.5,ymin=-Inf,ymax=Inf),alpha=0.05,fill="#E41A1C") +
geom_rect(aes(xmin=3.5,xmax=6.5,ymin=-Inf,ymax=Inf),alpha=0.05,fill="#377EB8") +
geom_bar(stat='identity', position=position_dodge()) +
coord_flip() +
scale_x_continuous(breaks=df$x, labels=df$a)
So I need a legend describing my two geom_rect areas. I was not able to map my two areas in any way to get a legend. In general the column df$b is describing the areas I do now by hand.
You can set colour= to variable b inside the aes() of both geom_rect(). This will make lines around the rectangles and also make legend. Lines can be removed setting size=0 for geom_rect(). Now using guides() and override.aes= you can change fill= for legend key.
ggplot(df, aes(x, c, fill=d, group=b)) +
geom_rect(aes(xmin=0.5,xmax=3.5,ymin=-Inf,ymax=Inf,colour=b),alpha=0.05,fill="#E41A1C",size=0) +
geom_rect(aes(xmin=3.5,xmax=6.5,ymin=-Inf,ymax=Inf,colour=b),alpha=0.05,fill="#377EB8",size=0) +
geom_bar(stat='identity', position=position_dodge()) +
coord_flip() +
scale_x_continuous(breaks=df$x, labels=df$a)+
guides(colour=guide_legend(override.aes=list(fill=c("#E41A1C","#377EB8"),alpha=0.3)))

Using a pre-defined color palette in ggplot

Does anyone know how to use a pre-defined color palette in ggplot?
I have a vector of colors I would like to use:
rhg_cols <- c("#771C19", "#AA3929", "#E25033", "#F27314", "#F8A31B",
"#E2C59F", "#B6C5CC", "#8E9CA3", "#556670", "#000000")
But when I try to pass it to nothing happened
ggplot(mydata, aes(factor(phone_partner_products)), color = rhg_cols) +
geom_bar()
You must put colour = rhg_cols inside aes(). As far as I can tell, you want to apply gradient to bars (in barplot) with factor variable on the abscissa? Then use fill - try this instead:
ggplot(mydata, aes(factor(phone_partner_products), fill = factor(phone_partner_products))) +
geom_bar() +
scale_fill_manual(values = rhg_cols)
or try to achieve approximate replica with:
ggplot(mydata, aes(factor(phone_partner_products), fill = phone_partner_products))) +
geom_bar() +
scale_fill_gradient(low = "#771C19", high = "#000000")
Notice that in second case a continuous variable is passed to fill aesthetics, therefore scale_fill_gradient is passed afterwards. If you pass a factor to the fill aes, you must stick with scale_fill_manual(values = rhg_cols).
If the colours are a palette, use scale_colour_manual:
ggplot(mydata, aes(factor(phone_partner_products), colour = colour_variable)) +
scale_colour_manual(values = rhg_cols)
First add, the colours to your data set:
mydata$col <- rhg_cols
Then map colour to that column and use scale_colour_identity
ggplot(mydata, aes(factor(phone_partner_products, colour = col))) +
geom_bar() +
scale_colour_identity()
Since the colors you want ARE the values in the color aesthetic, what you really want is the identity scale, in this case scale_fill_identity.
ggplot(mydata, aes(factor(phone_partner_products)), color=rhg_cols) +
geom_bar() +
scale_fill_identity())
Since you didn't supply data, I'm going to use a slightly different example using your color data:
rhg_cols <- c("#771C19","#AA3929","#E25033","#F27314","#F8A31B",
"#E2C59F","#B6C5CC","#8E9CA3","#556670","#000000")
mydata <- sample(rhg_cols, 100, replace = TRUE)
qplot(mydata, fill = mydata) +
scale_fill_identity()
note: I omitted + opts(axis.text.x=theme_text(angle=90)) for clarity in the example.

Resources