Adding legend to bar chart with data from two data frames - r

I have two plots I just want to know how I can add a legend for the blue and gray bar charts and also could you please show me how you could also edit the legend tittle.
X1 <- c(seq(7.912087912,44.83516484,1.538461538))
X2 <- c(seq(7.912087912,49.45054945,1.538461538))
dat2 <- data.frame(x = X2 , y = rnorm(28, 26, 5))
dat1 <- data.frame(x = X1 , y = rnorm(100, 25, 4))
ggplot(NULL) +
geom_bar(dat1, mapping = aes(x = x, y = y), stat = "identity",alpha = 0.3, position = "stack" ) + labs( x = " Time [ S ]", y = "Frequency") + theme_minimal() +
ggtitle("Histogram Of Time In Tank") + theme(plot.title = element_text(hjust = 0.5)) +
theme(plot.title = element_text(hjust = 0.5)) +
geom_bar(dat2, mapping = aes(x = x, y = y ), stat = "identity", alpha = .3, position = "stack", fill='lightblue' , color='lightblue4')
+ scale_linetype_discrete(name = LegendTitle)

If you want a legend in ggplot, you need to have an aesthetic mapping inside your aes() or no legend will appear. Here's how we can set a mapping and then use the scale to set the colors we want
ggplot(NULL) +
geom_bar(dat1, mapping = aes(x = x, y = y, fill="Grey Bars"), stat = "identity",alpha = 0.3, position = "stack" ) +
labs( x = " Time [ S ]", y = "Frequency") +
theme_minimal() +
ggtitle("Histogram Of Time In Tank") +
theme(plot.title = element_text(hjust = 0.5)) +
geom_bar(dat2, mapping = aes(x = x, y = y, fill='Blue Bars') , stat = "identity", alpha = .3, position = "stack", color='lightblue4') +
scale_fill_manual(name="Bars", values=c("Grey Bars" = "grey35", "Blue Bars" = "lightblue"))

Related

change starting value for geom_bar

I have a plot that includes data from two different scales. So far, I've plotted both variables and adjusted the scale of one variable (ss) so that it is closer to the other variables. This greatly reduced the white space in the middle of the plot.
set.seed = 42
df <- data.frame(
cat = runif(10, 1, 20),
mean = runif(10, 350, 450),
ss = runif(10, 1, 50))
ggplot(data = df) +
geom_bar(aes(x = cat, y = ss + 250),
stat = "identity",
fill = "red") +
geom_point(aes(x = cat, y = mean)) +
geom_smooth(aes(x = cat, y = mean),
method = "loess", se = TRUE) +
scale_y_continuous(sec.axis = sec_axis(trans = ~.-250,
name = "sample size")) +
labs(y = "mean") +
theme_bw()
However, I don't love the really long bars for sample size, and I'd like to change the limits on the left y axis so that it starts 250 (where ss = 0). Unfortunately, if I replace my current scale_y_continuous parameter with limits (see below), then the bars disappear. How do I do this?
ggplot(data = df) +
geom_bar(aes(x = cat, y = ss + 250),
stat = "identity",
fill = "red") +
geom_point(aes(x = cat, y = mean)) +
geom_smooth(aes(x = cat, y = mean),
method = "loess", se = TRUE) +
scale_y_continuous(limits = c(250, 510), ### NEW Y AXIS LIMITS
sec.axis = sec_axis(trans = ~.-250,
name = "sample size")) +
labs(y = "mean") +
theme_bw()
EDIT: Updated plot with #AllanCameron's suggestion. This is really close, but it has the values of the bars extend below 0 on the secondary axis.
ggplot(data = df) +
geom_bar(aes(x = cat, y = ss + 250),
stat = "identity",
fill = "red") +
geom_point(aes(x = cat, y = mean)) +
geom_smooth(aes(x = cat, y = mean),
method = "loess", se = TRUE) +
scale_y_continuous(sec.axis = sec_axis(trans = ~.-250,
name = "sample size")) +
labs(y = "mean") +
theme_bw() +
coord_cartesian(ylim = c(250, 510)) ### NEW
Just expand parameter in scale_y_continuous() to c(0,0).
This tells ggplot2 to not add padding to the plot box.
ggplot(data = df) +
geom_bar(aes(x = cat, y = ss + 250),
stat = "identity",
fill = "red") +
geom_point(aes(x = cat, y = mean)) +
geom_smooth(aes(x = cat, y = mean),
method = "loess", se = TRUE) +
scale_y_continuous(sec.axis = sec_axis(trans = ~.-250, name = "sample size"),
expand = c(0,0)) + # New line here!
labs(y = "mean") +
theme_bw() +
coord_cartesian(ylim = c(250, 510))

sorting the labels alphabetically when they appear on the y bar

For the example below, I wonder to know how can I have the labels sorted alphabetically when they appear on the y bar.
Thanks,
NM
# Create labels for plot
boxLabels = c("Package recommendation", "Breeder’s recommendations", "Vet’s
recommendation", "Measuring cup", "Weigh on scales", "Certain number of
cans", "Ad lib feeding", "Adjusted for body weight")
df <- data.frame(yAxis = length(boxLabels):1,
boxOdds =
c(2.23189,1.315737,1.22866,.8197413,.9802449,.9786673,.6559005,.5929812),
boxCILow =
c(.7543566,1.016,.9674772,.6463458,.9643047,.864922,.4965308,.3572142),
boxCIHigh =
c(6.603418,1.703902,1.560353,1.039654,.9964486,1.107371,.8664225,.9843584)
)
(p <- ggplot(df, aes(x = boxOdds, y = boxLabels)) +
geom_vline(aes(xintercept = 1), size = .25, linetype = 'dashed') +
geom_errorbarh(aes(xmax = boxCIHigh, xmin = boxCILow), size = .5, height =
.2, color = 'gray50') +
geom_point(size = 3.5, color = 'orange') +
theme_bw() +
theme(panel.grid.minor = element_blank()) +
scale_x_continuous(breaks = seq(0,7,1) ) +
coord_trans(x = 'log10') +
ylab('') +
xlab('Odds ratio (log scale)') +
annotate(geom = 'text', y =1.1, x = 3.5, label ='Model p < 0.001\nPseudo
R^2 = 0.10', size = 3.5, hjust = 0) + ggtitle('Intention to remove box
turtles from the road')
)
the values are shown in alphabetical order but from bottom to top. to reverse, you could try using fct_rev from the forcats package:
replace y = boxLabels with
y = forcats::fct_rev(boxLabels)

Adding text labels over barplot with ggplotly in R

I have the following dataframe in R
DF_1<-data.frame("ID"=c("A_1", "A_2"), 'Sum'= c(2500,12500), "RR"=
c(95,95), "CC"= c(50,50), "nn"=c(4,4), "DP"= c(12.5,100))
I have created the following barplot with text written in the barplot as follows
p2<-ggplot(data = DF_1, mapping = aes(x = ID, y = DP,
fill=str_wrap(ID,10))) + geom_bar(stat = 'identity', width = .35, position
= "dodge")+ geom_text(aes(label=RR) , position = position_dodge(0.9),vjust
= 2,check_overlap = TRUE)+geom_text(aes(label=CC) , position = postion_dodge(0.9),vjust = 4,check_overlap = TRUE)+ geom_text(aes(label=nn) , position = position_dodge(0.9),vjust = 6,check_overlap = TRUE)+ labs(fill = "LEGEND")+labs(x = "XLabels", y= "DPP")+theme(legend.key.height = unit( 2 ,"cm"))+theme(axis.text.x=element_blank())+ggtitle("DPPCHART")+ theme(plot.title = element_text(hjust = 0.5))
In the plot so generated the three text labels are generated clearly on the barplot. The next step is to make dynamic ticks work
p<-ggplotly(p, dynamicticks=T)
Now the three text labels overlap each other.
Is there a way to retain the text labels separately when using ggplotly.
You can use HTML directly inside the labels like this to remove the overlap:
library(stringr)
library(ggplot2)
library(plotly)
DF_1 <- data.frame("ID"=c("A_1", "A_2"), 'Sum'= c(2500,12500),
"RR"= c(95,95), "CC"= c(50,50), "nn"=c(4,4), "DP"= c(12.5,100))
p <- ggplot(data = DF_1, mapping = aes(x = ID, y = DP,fill=str_wrap(ID,10))) +
geom_bar(stat = 'identity', width = .35, position = "dodge") +
geom_text(aes(label=paste0(RR, "<br>", CC, "<br>", nn)) ,
position = position_dodge(0.9), vjust = 2, check_overlap = TRUE) +
labs(fill = "LEGEND") + labs(x = "XLabels", y= "DPP") +
theme(legend.key.height = unit( 2 ,"cm")) +
theme(axis.text.x=element_blank()) +
ggtitle("DPPCHART") +
theme(plot.title = element_text(hjust = 0.5)) +
scale_y_continuous(limits = c(0,110))
ggplotly(p) # can use with or without dynamicTicks=TRUE
Output is:

barplot with lineplot - secondary axis

After referring to multiple links i have got to the below code however i still am not succeeding to get the line with labels. I suspect some mistake in sec.axis transformation but i can't figure it out.
# dummy data
df_dummy = data.frame('Plan_code'=c('A','B','C','D','E','F','G'),
'Total'=c(191432,180241,99164,58443,56616,29579,19510),'STP'=c(41,40,44,37,37,37,45))
# creation of plot
[![g <- ggplot(data = df_dummy, aes(x = Plan_code, y = Total)) +
geom_col(aes(fill = 'Total')) +
geom_line(data = df_dummy, aes(x = Plan_code, y = STP,group=1)) +
geom_point(data = df_dummy, aes(x = Plan_code,y=STP)) +
geom_label(data = df_dummy, aes(x = Plan_code, y = STP, fill = Plan_code, label = paste0('%', STP)), color = 'white', vjust = 1.6, size = 3) +
scale_y_continuous(sec.axis = sec_axis(~. / 2000, name = 'PERCENT')) +
labs(fill = NULL, color = NULL) +
theme_minimal()
print(g)][1]][1]
Like that?
g <- ggplot(data = df_dummy, aes(x = Plan_code, y = Total)) +
geom_col(aes(fill = 'Total')) +
geom_point(data = df_dummy, aes(x = Plan_code,y=STP * 2000)) +
geom_label(data = df_dummy, aes(x = Plan_code, y = STP *2000, fill = Plan_code, label = paste0('%', STP)), color = 'white', vjust = 1.6, size = 3) +
scale_y_continuous(sec.axis = sec_axis(~. / 2000, name = 'PERCENT'))+
geom_line(data = df_dummy, aes(x = Plan_code, y = STP * 2000,group=1), col = 'blue') +
theme(axis.text.y.right = element_text(color = 'blue'),axis.title.y.right = element_text(color = 'blue'))
labs(fill = NULL, color = NULL) +
theme_minimal()
I just multiplied your data with 2000, so that the absolute y-coordinates were right.
And I changed the color.

Labeling a point by giving its x and y axes on geom_histogram

How to show the point (x=0, y=1500) with a text label next to it on the following histogram?
ggplot(ds_visits, aes(x = patientsInService)) +
geom_histogram(stat = "count", col = "black", fill = "white") +
theme_bw() +
labs(x = "Patients in service", y = "Cases") +
scale_x_discrete(limits = seq(0, 5, 1))
You have to create dummy data.frame for point data:
pointData <- data.frame(X = 0, Y = 1500)
Plot it with with two additional gems (geom_point and geom_text):
ggplot(ds_visits, aes(patientsInService)) +
geom_histogram(stat = "count", col = "black", fill = "white") +
geom_point(data = pointData, aes(X , Y)) +
geom_text(data = pointData, aes(X + 1 , Y + 10, label = "My Text"))
In geom_text I'm changing coordinates a little bit not to overlap text with point.

Resources