Pie charts in ggplot2 with variable pie sizes - r

I've tried various ways to get a facet_grid of pie charts in ggplot2 to vary width/radii according to another variable (strength).
geom_bar accepts width=0.5 as a parameter but it is ignored once coord_polar is added. Adding width=0.5 to the ggplot aes or adding a aes to geom_bar doesn't work. I can't see any other relevant options for coord_polar. What's the easiest way to do this? The code below makes a nice grid of pie charts but doesn't change the sizes of the pie charts. What am I missing?
mydata <- data.frame(side1=rep(LETTERS[1:3],3,each=9),
side2=rep(LETTERS[1:3],9,each=3),
widget=rep(c("X","Y","Z"),9*3),
val=runif(9*3),
strength=rep(c(1,2,3),3,each=3))
ggplot(mydata, aes(x="",y = val, fill = widget, width = strength)) +
geom_bar(position="fill") +
facet_grid(side1 ~ side2) +
coord_polar("y") +
opts(axis.text.x = theme_blank())

Do you mean like this?
ggplot(mydata, aes(x=strength/2, y = val, fill = widget, width = strength)) +
geom_bar(position="fill", stat="identity") +
facet_grid(side1 ~ side2) +
coord_polar("y") +
opts(axis.text.x = theme_blank())

Related

unstack stacked ggplot legend

I'm working with a chemistry dataset, where I have 11 different chemicals, here labeled under the column c1,c2,...c11
I have made pie charts using library(ggplot2) , and would like to do 2 things with my plot.
Display all variables in the legend in a horizontal fashion (done), and not have them stacked (not done), as you see in my example. Having just one line would be great. 2 lines could also be acceptable.
Change colors to be color-blind friendly
Here is a pretend dataset we can work with so you can see what I have at this point. I have tried searching "legend margins" to increase the area the legend is plotted on, but to no avail.
data <- read.delim("https://pastebin.com/raw/MS5GLAxa", header = T)
ggplot(data, aes(x="", y=ratio, fill=chemical)) +
geom_bar(stat="identity", width=1,position = position_fill()) + facet_wrap(~treatment, nrow=1)+
coord_polar("y", start=0)+
theme_void(base_size = 20)+
theme(legend.position=c(0.5, 1.2),legend.direction = "horizontal")+
theme(plot.margin=unit(c(0,0,0,0), 'cm'))
Some side bonuses here would be to be able to:
increase the size of the pie chart (I believe I achieved this with making my margins as small as possible on the sides)
have the pie chart have solid colors, and no white lines in graph
Use guides to make the number of rows to 1 and use scale_fill_brewer with color blindness friendly palette.
ggplot(data, aes(x="", y=ratio, fill=chemical)) +
geom_bar(stat="identity", width=1,position = position_fill()) +
facet_wrap(~treatment, nrow=1)+
coord_polar("y", start=0) +
scale_fill_brewer(palette="Paired") +
theme_void(base_size = 20) +
theme(legend.position=c(0.5, 1.5),legend.direction = "horizontal",
plot.margin=unit(c(0,0,0,0), 'cm')) +
guides(fill = guide_legend(nrow = 1)) # if required nrow = 2

ggplot - geom_text with free scales facet_wrap

I have the following data:
thedata <- data.frame(value= c(90,100,2,10)
,category1 = c("A","A","B","B")
,category2 = c("C","D","C","D"))
And I am looking to produce the following figure with labels just to the outside of the bars:
ggplot(thedata, aes(x=category2, y=value)) +
geom_bar(stat="identity", position="dodge", fill = "grey") +
facet_wrap(~category1, scales = "free_x") +
coord_flip() +
geom_text(aes(label=value, hjust = -0.35))
Using this method the labels fall outside the chart range. If the expand_limits argument is used it overwrites the scales = "free_x" argument. Any suggestions for say, adding an extra 10% space to each of the chart to accommodate the labels?
Use the expand argument of scale_y_continuous. See ?continuous_scale for details.

fill and scale_color in ggplot

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.

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?

geom_text with faceted barplot messes up scales

Trying to facet out a barplot of survey responses. Each facet should have the percent answers to the question while annotating each facet with the number of respondants. Everything seems to work fine until add the annotation with geom_text which messes up the scale. Cant figure out why.
This seems to work fine
ggplot(dat2, aes(Q1a)) +geom_bar(aes(y = ..prop.., group = D3b) ) +
coord_flip() + facet_wrap(~ D3b) + labs(x="",y="") +
scale_y_continuous(labels = percent)
and gets me this, which has the barplots scaled the way I need them
But when I add geom_text the scale gets all messed up
ggplot(dat2, aes(Q1a)) +geom_bar(aes(y = ..prop.., group = D3b) )+
coord_flip() + facet_wrap(~ D3b) + labs(x="",y="") +
scale_y_continuous(labels = percent)+ geom_text(data=dat2.cor,
aes(x=0,y=0,label=n), nudge_x = 10, nudge_y=20,
colour="black",inherit.aes=FALSE)
Like so:
dat2.cor is a separate dataset I created with data annotate the facets which looks like this:
Anybody have any idea whats going on here?

Resources