This question already has answers here:
Showing data values on stacked bar chart in ggplot2
(3 answers)
Closed 5 years ago.
I've created a stacked barchart and faceted using two variables. I'm unable to position the values in the barchart in the middle, it either appears at the extremes or overlaps. The expected image is the following:
I've pasted the script below. Any help would be appreciated.
library(dplyr)
library(reshape2)
library(ggplot2)
year<-c("2000","2000","2010","2010","2000","2000","2010","2010")
area<-c("Rural","Rural","Rural","Rural","Urban","Urban","Urban","Urban")
sex<-c("Male","Female","Male","Female","Male","Female","Male","Female")
city<-c(58,61,74,65,51,55,81,54)`
village<-c(29,30,20,18,42,40,14,29)
town<-c(13,9,6,17,7,5,5,17)
data<-cbind.data.frame(year,area,sex,city,village,town)
dre<-melt(data,id.vars = c("year","area","sex"))
dre <- arrange(dre,year,area,sex,variable) %>%
mutate(pos = cumsum(value) - (0.5 * value))
a <- ggplot(dre,aes(factor(sex),value,fill=variable)) +
geom_bar(stat='identity',position="stack")
b <- a +
facet_wrap(factor(year)~area)
c <- b +
geom_text(aes(label=paste0(value,"%"),y=pos),
position="stack",size=2,hjust=0.85,color="black")
d <- c +
coord_flip() +
theme_bw() +
scale_fill_brewer()
print(d)
You no longer need to calculate the position variable. Starting in ggplot2_2.2.0, text can be stacked and centered via position_stack.
The relevant line of geom_text code is below. Notice I don't need to use the "pos" variable at all for text placement.
geom_text(aes(label=paste0(value,"%")),
position = position_stack(vjust = .5), size = 2, color = "black")
The code for the plot and the resulting graph:
ggplot(dre, aes(factor(sex), value, fill = variable)) +
geom_col() +
facet_wrap(factor(year)~area) +
geom_text(aes(label = paste0(value,"%")),
position = position_stack(vjust = .5), size = 2, color = "black") +
coord_flip() +
theme_bw() +
scale_fill_brewer()
Related
This question already has answers here:
ggplot, facet, piechart: placing text in the middle of pie chart slices
(4 answers)
Display percentage values on a pie chart [duplicate]
(1 answer)
R + ggplot2 => add labels on facet pie chart [duplicate]
(1 answer)
Closed 2 years ago.
I want to add percent value to this chart to this data frame
s<-# Basic piechart
ggplot(heart, aes(x="", y="", fill=sex)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0)
plot(s)
You haven't shared your data, but your plot code implies that heart is a data frame that includes a column labeled sex which is either of factor or character class, so this toy data set should suffice to demonstrate.
set.seed(1)
heart <- data.frame(sex = sample(c("Male", "Female"), 24, TRUE))
Your plotting code is actually stacking all the males, then all the females, without counting them, so there is no way for the geom_text to know where in this stack it should be plotting. Instead, you need to use the default stat of geom_bar, which is stat = "count", then plot the geom_text at the appropriate points:
library(ggplot2)
ggplot(heart, aes(x = "", fill = sex)) +
geom_bar(width = 1) +
geom_text(data = as.data.frame(table(heart$sex)),
aes(group = Var1, label = scales::percent(Freq / sum(Freq)),
y = Freq, fill = Var1),
position = position_stack(vjust = 0.5)) +
coord_polar("y", start = 0) +
theme_void()
#> Warning: Ignoring unknown aesthetics: fill
Created on 2020-11-19 by the reprex package (v0.3.0)
This question already has an answer here:
ggplot2: How to specify multiple fill colors for points that are connected by lines of different colors
(1 answer)
Closed 4 years ago.
I created a violin plot in R, and I want to change part of the dots color and size. This change will be according to an attribute of True/False in the data file.
This is how I tried it:
p <- ggplot(data, aes(order,count),levels=data_levels) +
geom_point(aes(colour = actor(data$color)))+
geom_violin(draw_quantiles = c(0.5),adjust = 2,size =0.4)+
geom_jitter(height = 0, width = 0.1,size =0.6)+
coord_flip()
boolColors <- as.character(c("False"="black", "True"="red"))
boolScale <- scale_colour_manual(name="color", values=boolColors)
p1 <- p + boolScale
I tried changing the size with scale_size_manual but it didn't work.
Without the data, it is had to know exactly what is wrong. But here is an example of setting a custom colour scale for points over a violin plot.
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_violin() +
geom_jitter(height = 0, width = 0.1, aes(colour = factor(gear))) +
scale_colour_manual(name="colour", values=c("pink", "purple", "orange"))
This question already has answers here:
What is the simplest method to fill the area under a geom_freqpoly line?
(4 answers)
Closed 6 years ago.
I am plotting a continuous variable in X-axis against the the corresponding counts (not the density) in the Y-axis using ggplot2.
This is my code
p <- ggplot(matched.frame, aes(x = AGE, color = as.factor(DRUG_KEY))) + geom_freqpoly(binwidth=5)
p1 <- p + theme_minimal()
plot(p1)
This produces a graph like this this:
I want the areas under these lines to be filled with colors and with little bit of transparency. I know to do this for density plots in ggplot2, but I am stuck with this frequency polygon.
Also, how do I change the legends on the right side? For example, I want 'Cases' instead of 26 and Controls instead of '27'. Instead of as.factor(DRUG_KEY), I want it to appear as 'Colors"
Sample data
matched.frame <- data.frame("AGE"=c(18,19,20,21,22,23,24,25,26,26,27,18,19,20,24,23,23,23,22,30,28,89,30,20,23))
matched.frame$DRUG_KEY <- 26
matched.frame$DRUG_KEY[11:25] <- 27
You can use geom_ribbon to fill the area under the curves and scale_fill_discrete (fill color) as well as scale_color_discrete (line color) to change the legend labels:
library(ggplot2)
set.seed(1)
df <- data.frame(x = 1:10, y = runif(20), f = gl(2, 10))
ggplot(df, aes(x=x, ymin=0, ymax=y, fill=f)) +
geom_ribbon(, alpha=.5) +
scale_fill_discrete(labels = c("1"="foo", "2"="bar"), name = "Labels")
With regards to your edit:
ggplot(matched.frame, aes(x=AGE, fill=as.factor(DRUG_KEY), color=as.factor(DRUG_KEY))) +
stat_bin(aes(ymax=..count..,), alpha=.5, ymin=0, geom="ribbon", binwidth =5, position="identity", pad=TRUE) +
geom_freqpoly(binwidth=5, size=2) +
scale_fill_discrete(labels = c("26"="foo", "27"="bar"), name = "Labels") +
scale_color_discrete(labels = c("26"="foo", "27"="bar"), name = "Labels")
This question already has answers here:
How to move or position a legend in ggplot2
(4 answers)
Closed 7 years ago.
I have created the following heatmap. If you notice that the legend for cohort is on the right and the vertically placed.
How do I move the legend to the bottom in order to give more space for X axis variable month M0 to M55...Also, you will notice that X axis elements are overlapping hence not clear.
Output of the graph:
cohort.clients<-df1
cohort.clients$cohort<-as.character(cohort.clients$cohort)
#we need to melt data
cohort.chart.cl <- melt(cohort.clients, id.vars = 'cohort')
colnames(cohort.chart.cl) <- c('cohort', 'month', 'clients')
#define palette
reds <- colorRampPalette(c('light green',"dark green","yellow"))
#plot data
p <- ggplot(cohort.chart.cl, aes(x=month, y=clients, group=cohort))
p + geom_area(aes(fill = cohort)) +
scale_fill_manual(values = reds(nrow(cohort.clients))) +
ggtitle('Customer Cohort')
Try something like:
ggplot(cohort.chart.cl, aes(x=month, y=clients, group=cohort))
geom_area(aes(fill = cohort)) +
scale_fill_manual(values = reds(nrow(cohort.clients))) +
ggtitle('Customer Cohort') +
theme(axis.text.x = element_text(angle = 45, hjust = 1),
legend.direction = "horizontal", legend.position = "bottom"))
It's also worth noting that your color palette is essentially the same color. If you make cohort$month a factor then ggplot should automatically give you a much more informative palette by default. That being said, with >50 categories, you're well past the realm of a distinguishable colors and might also consider binning the months (into yearly quarters?) and returning to a spectrum like you have now.
This question already has answers here:
ggplot, facet, piechart: placing text in the middle of pie chart slices
(4 answers)
Closed 7 years ago.
My df looks like:
1 with score
125 without score
I'd like to make piechart in ggplot:
ggplot(data = df_pp, aes(x = "", y = Number/sum(Number),fill = PolyPhen_score)) + geom_bar(stat="identity") + coord_polar(theta='y') +
ggtitle("Variants with PolyPhen score and without PolyPhen score") +
scale_y_continuous(labels = percent) + labs(x = "", y = "") +
theme(panel.background = element_rect(fill = 'white')) +
geom_text(aes(label = paste(round(Number/sum(Number)*100),"%")),vjust = 5)
But my labels 1% and 99% are overlapped on the piechart.
If I add this code, it doesn't help:
geom_text(aes(y=Number/2 + c(0,cumsum(Number)[-length(Number)]), label = percent(Number/100)), size=5)
Maybe these other Stackoverflow questions can help you:
ggplot, facet, piechart: placing text in the middle of piechart slices
R + ggplot2 => add labels on facet pie chart
I did few tests on my machine with some random data and I tried with this:
geom_text(aes(x = 1.7, y=cumsum(Number/sum(Number)) - Number/sum(Number)/2, label = paste(round(Number/sum(Number)*100),"%")), size = 6)
X is the distance of labels from the center of the pie. x = 1.7 gives me a nice result with my data in RStudio, but probably you will need different values.