Reputation: 1080
I have the below data set and r code to generate the ggplot.
df = data.frame(Animals = c("Dog", "Cat", "Horse", "Giraffe"), Number = c(88, 11, 107, 59),
Cat = c("A", "A", "B", "B"),
Place=c("Place1","Place2"))
ggplot(df, aes(Animals, Cat, fill=Number)) +
geom_tile() +
scale_fill_gradient2(low= "red", high = "green",
mid = "orange",
midpoint = 50,
space = "Lab")+
geom_text(label=df$Number)+
facet_grid(.~Place)
output of the above code is,
if you see the graph, the gradient fill is not as mentioned in the code. as per the code the higher number should be in green.
Need some expert view on this.
Upvotes: 5
Views: 906
Reputation: 93871
The gradient fill is correct. It's the text values that are incorrect. Note, for example, in the data below that Horse
and B
have a value of 107, but the text value for that tile in your plot is 11.
Animals Number Cat Place
1 Dog 88 A Place1
2 Cat 11 A Place2
3 Horse 107 B Place1
4 Giraffe 59 B Place2
Change to geom_text(aes(label=Number))
. By using geom_text(label=df$Number)
, you're reaching outside the ggplot environment to the global environment version of df
, in which the values of Number
are (as ordered in the data frame), 88, 11, 107, 59. So that's the order in which the numbers are plotted (from left to right) in the graph. However, by mapping Number
to label
, by using aes(label=Number)
, you ensure that the label
aesthetic and the fill
aesthetic are both mapped to the graph in a corresponding way as determined by the "natural" logic of ggplot
geoms and aesthetic mappings.
ggplot(df, aes(Animals, Cat, fill=Number)) +
geom_tile() +
scale_fill_gradient2(low= "red", high = "green", mid = "orange",
midpoint = 50, space = "Lab")+
geom_text(aes(label=Number)) +
facet_grid(.~Place)
This appears to be a toy example, but I thought I'd also point out that you can have ggplot remove space for empty values by using scales="free_x"
when you facet:
ggplot(df, aes(Animals, Cat, fill=Number)) +
geom_tile() +
scale_fill_gradient2(low= "red", high = "green", mid = "orange",
midpoint = 50, space = "Lab")+
geom_text(aes(label=Number)) +
facet_grid(.~Place, scales="free_x")
Upvotes: 6