I created an animated bar chart but the label value is not right. I don't know why cum_2 in my data is an integer, but in the resulting gif the label text appears as a real number (example: 674.5... instead of 675).
library(tidyverse)
library(gganimate)
df <- data.frame(date = c(rep('2020-07-08',4), rep('2020-07-09',4),
rep('2020-07-10',4), rep('2020-07-11',4),
rep('2020-07-12',4)),
sub = rep(c("PYTHON", "SQL", "VBA", "R"),5),
cum_2 = c(659,609,454,450,659,609,468,450,670,609,478,450,670, 609,486,461,679,609,486,469),
rank = rep(c(1,2,3,4),5))
fill <- c('red','blue','green','orange') # example fill colors
df %>%
ggplot(aes(rank, y = cum_2,
fill = sub)) +
geom_col(alpha = 0.6)+
scale_fill_manual(values = fill) +
geom_text(aes(y = 0,
label = paste(sub, " ")),
vjust = 0.2,
hjust = 1) +
transition_states(states = date,transition_length = 4, state_length = 1) +
geom_text(aes(y = cum_2,
label = round(cum_2,0),
hjust = 0,
size = 12)) +
scale_x_reverse() +
coord_flip(clip = "off", expand = FALSE) +
guides(color = FALSE, fill = FALSE) +
theme(axis.line=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
legend.position="none",
panel.background=element_blank(),
panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
panel.grid.major.x = element_line( size=.1, color="grey" ),
panel.grid.minor.x = element_line( size=.1, color="grey" ),
plot.title=element_text(size=25, hjust=0.5, face="bold", colour="grey", vjust=-1),
plot.subtitle=element_text(size=18, hjust=0.5, face="italic", color="grey"),
plot.caption =element_text(size=8, hjust=0.5, face="italic", color="grey"),
plot.background=element_blank(),
plot.margin = margin(2,2, 2, 4, "cm")) +
labs(title = 'MCI Vietnam : {closest_state}',
subtitle = "Number of students") +
view_follow(fixed_x = TRUE) +
enter_fade() +
exit_shrink() +
ease_aes('sine-in-out') -> anim
# gif
animate(anim, nframes = length(unique(df$date)),
detail = 5,
fps = 5,
# duration = 20,
renderer = gifski_renderer("file.gif"))
Last plot in gif file here:
Thanks all for read & support me.
Since the y position of the bars is tweened in the animation (cum_2 in your data frame), and the label position and text are based on cum_2, it will also get tweened and the result is that you have numbers with lots of decimal places appearing as a result.
Luckily, the fix is pretty easy: just force your label to be evaluated as.character(). Change your geom_text line to read as follows, and that fixes the issue:
geom_text(aes(y = cum_2, label = as.character(round(cum_2,0)),
hjust = 0, size = 12))
Here's the result (saved with duration=5):
*FYI: your code was missing the colors you used, so here I defined fill=c('red','blue','green','orange').
Related
I've been working with this code for a while but this is the first time I've only had two categories on my x-axis. For some reason, R will not space out the bins and instead bunches them at the beginning. How do I evenly spread them along the x-axis?
xlabels<-c("A","B")
CTplot <- ggplot(CTsum, aes(x=Treatment, y=FI)) +
geom_col(fill="lightsteelblue") +
scale_x_discrete(labels= xlabels)+xlab("")+ylab("")+
theme(panel.background = element_blank(),axis.line = element_line(colour = "black"),axis.text.x = element_text(size=20,color="black"), axis.text.y = element_text(size=20, color="black"), axis.title.x = element_text(size=25), axis.title.y = element_text(size=25))+
geom_errorbar(aes(ymin = FI - meanse, ymax = FI + meanse, width=0.2))+
annotate("text",x=1,y=0.84, label="A",size=5)+
annotate("text",x=2,y=0.62, label="B",size=5)+
annotate("text",x=3,y=0.29, label="",size=5)+
annotate("text",x=4,y=0.26, label="",size=5)+
annotate("text",x=0.65,y=0.5, label="",size=15)
CTplot
When you plot categorical data on the x axis, you are "really" plotting at integer values x = 1, x = 2, etc, but with the text labels used in place of numbers. This is what allows you to put text annotations at x = 1 and x = 2.
However, the bars are bunched at the left because you have added two empty text annotations over to the right (at position x = 3 and x = 4). The plot has expanded right to accommodate them. Since they are empty anyway, you don't need them. Here is the plot without them:
CTplot <- ggplot(CTsum, aes(Treatment, FI)) +
geom_col(fill = "lightsteelblue") +
geom_errorbar(aes(ymin = FI - meanse, ymax = FI + meanse, width = 0.2)) +
scale_x_discrete(labels = xlabels) +
xlab("") +
ylab("") +
theme(panel.background = element_blank(),
axis.line = element_line(colour = "black"),
axis.text.x = element_text(size=20,color="black"),
axis.text.y = element_text(size=20, color="black"),
axis.title.x = element_text(size=25),
axis.title.y = element_text(size=25))+
annotate("text",x=1,y=0.84,label="A",size = 5) +
annotate("text",x=2,y=0.62,label="B",size = 5)
CTplot
And here it is with an empty annotation at x = 4:
CTplot + annotate("text",x = 4, y = 0.29, label = "", size = 5)
To emphasise the point, let's see an empty annotation at x = 20:
CTplot + annotate("text",x = 20, y = 0.29, label = "", size = 5)
As you can see, the x axis has had to expand to accommodate the invisible text annotation at x = 20.
If you want the bars a bit more spread out, you can do something like:
CTplot <- ggplot(CTsum, aes(Treatment, FI)) +
geom_col(fill = "lightsteelblue", width = 0.6) +
geom_errorbar(aes(ymin = FI - meanse, ymax = FI + meanse, width = 0.2)) +
scale_x_discrete(labels = xlabels, expand = c(0.75, 0)) +
xlab("") +
ylab("") +
theme(panel.background = element_blank(),
axis.line = element_line(colour = "black"),
axis.text.x = element_text(size=20,color="black"),
axis.text.y = element_text(size=20, color="black"),
axis.title.x = element_text(size=25),
axis.title.y = element_text(size=25))+
annotate("text",x=1,y=0.84,label="A",size = 5) +
annotate("text",x=2,y=0.62,label="B",size = 5)
CTplot
Data used (approximated from image in OP)
CTsum <- data.frame(Treatment = c("A", "B"), FI = c(0.71, 0.48), meanse = 0.1)
I have a plot whose margins are slightly askew and need to be removed. So there should be no empty grey along the bottom or at the left and right of the plot. The dots should go right against the axis's. I think part of the problems may be my last two annotation lines. I tried adding + theme(plot.margins = unit(c(0.1,0.1,0.1,0.1), "cm")) in the last line that defines my plot but this just returns an error:
Error: Theme element `plot.margins` is not defined in the element hierarchy.
`
pvalplot<-function(var, maintitle) {
pvalall<-as.data.frame(c(t(var)))
pvalall$Sample_Size<-c((1:(5*162)),(1:(11*162)),(1:(3*162)),(1:(5*162)),(1:(13*162)),(1:(3*162)),(1:(5*162)))
pvalall$Domain<-c(rep("Physical",5*162),rep("Perinatal",11*162),rep("Developmental",3*162),
rep("Lifestyle-Life Events",5*162),rep("Parental-Family",13*162),rep("School",3*162),
rep("Neighborhood",5*162))
pvalall$Domain <- factor(pvalall$Domain,
levels = c("Physical", "Perinatal", "Developmental",
"Lifestyle-Life Events", "Parental-Family",
"School","Neighborhood"))
pvalall[,1]<-ifelse(pvalall[,1]<1e-20,1e-20,pvalall[,1])
names(pvalall)[1]<-"P-Values"
pvalexp.labels= rep("",45*162)
for (i in c(1:45)){
j=i*162-81
pvalexp.labels[j]=rownames(var)[i]
} #makes list of empyt labels that w
p<-ggplot(pvalall,aes(x = 1:nrow(pvalall), y = -log10(pvalall[,1])))+
geom_point(aes(color = Domain,size=5),
alpha = 0.7, size=1)
p+ylab(expression(atop(" -log10(P-Values)")))+
ylim(0,20)+
xlab(element_blank())+
theme(legend.title=element_blank())+
scale_x_continuous( breaks=c(1:45)*162-81, labels = rownames(var))+
theme_classic()+
theme(axis.title.x = element_blank())+
theme(axis.ticks.x = element_blank())+
theme(axis.title.y = element_text(size = 25))+
theme(text = element_text(size=25))+
theme(legend.title=element_blank())+
theme(legend.position=c(0.8,0.7))+
geom_abline(slope=0,intercept=-log10(c(var)[astsa::FDR(c(var))]),linetype = "dashed")+
geom_abline(slope=0,intercept=5.2,linetype = "dashed")+
ggtitle(maintitle)+
theme(plot.title = element_text(hjust = 0.5))+
theme(
legend.box.background = element_rect(),
legend.box.margin = margin(6, 6, 6, 6))+
theme_update(axis.text.x = element_text(angle = 35, size = 6.5, vjust = 1, hjust=1, color = "black")) +
annotate("text", label = expression(paste("FDR P-value","=0.05")),size=5, x=1000,y=-log10(c(var)[astsa::FDR(c(var))])-0.5, color="black",parse=TRUE)+
annotate("text", label = expression(paste("Bonferroni P-value","=0.05")),size=5, x=1200,y=5.7, color="black",parse=TRUE)
}#end of plotting
You can insert a line
scale_y_continuous(expand = c(0, 0)) +
in your plot command chain.
I have the following code :
cols <- c("Bonus"=maroon ,
"Limit"=grey)
a <- ggplot(periodtreatments, aes(x=names, width=.2)) +
geom_point(aes(y=bonus_coefs, colour="Bonus"), stat="identity", position = position_nudge(x = -.1), shape=16) +
geom_point(aes(y=limit_coefs, colour="Limit"), stat="identity", position = position_nudge(x = .1), shape=15)+
geom_errorbar(aes(ymin=bonus_upper, ymax=bonus_lower, width=0.09), size =0.8, stat="identity", colour=maroon, position = position_nudge(x = -.1)) +
geom_errorbar(aes(ymin=limit_lower, ymax=limit_upper, width=0.09), size =0.8, stat="identity", colour=grey, position=position_nudge(x = .1)) +
scale_y_continuous(name="Treatment effect (minutes/day)") +
theme_classic() +
#theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(x = "") +
theme(legend.text.align = 0,
legend.key.height = unit(1, "cm"),
legend.position="bottom") +
theme(legend.margin=margin(0,0,0,0),
legend.box.margin=margin(-10,-10,-10,-10)) +
theme(axis.text.x = element_text(colour="black")) +
coord_cartesian(ylim = c(-70, 5)) +
theme(legend.text=element_text(size=11)) +
theme( # remove the vertical grid lines
panel.grid.major.x = element_blank() ,
# explicitly set the horizontal lines (or they will disappear too)
panel.grid.major.y = element_line( size=.05, color="grey" )
)+
scale_colour_manual(name = "", values=cols,
labels = c("Bonus", "Limit"))+
scale_shape_manual(name = "",
labels = c("Bonus", "Limit"),
values = c(16, 15))
But the "scale_shape_manual" legend does not work.
In fact here is what my plot look like
Why does the Bonus show as a sqaure whereas its shape is 16 = point ???
Please help me i am so helpless
How can I increase vertical spacing between legend keys:
p1 <- ggplot(data = HSS, mapping = aes(x = EVENT, y = HSS, fill = TIME)) +
geom_bar(stat = "identity",width=0.7, colour = "black", position = position_dodge(0.7)) +
scale_fill_manual("HSS", values = c("deepskyblue3", "indianred2"),
labels = c("1200 UTC (0.049)", "0000 UTC (0.031)")) + theme_bw()
p1 <- p1 + scale_y_continuous(expand = expansion(mult = c(0.0085, -0.085)),
limits = c(-0.03,0.5), breaks = c(-0.03,-0.01, 0.01, 0.03, 0.05, 0.07,0.09,0.11,0.13,0.15,0.17,
0.19, 0.21,0.23,0.25,0.27,0.29,0.31,0.33,0.45),
labels = c("-0.03","-0.01","0.01","0.03","0.05","0.07","0.09","0.11","0.13","0.15","0.17",
"0.19","0.21","0.23","0.25","0.27","0.29","0.31","0.33","0.45")) +
theme(axis.text.x=element_text(color = "black", size=12, face = "bold", angle=90, vjust=.5,
hjust=0.8)) +
theme(axis.text.y = element_text(color = "black", size=12, face = "bold"))
p1 <- p1 + theme( axis.line = element_line(colour = "black", size = 0.5, linetype = "solid")) +
labs( y = "HSS")
p1 <- p1 + theme(axis.title=element_text(colour = "blue2" ,size=14,face="bold", vjust = 0.1))
p1 <- p1 + theme(legend.position=c(0.98,0.98)) + theme(legend.title=element_blank(),
legend.text = element_text(face = "bold", size = "12"),
legend.box.background = element_rect(size=0.7, linetype="solid"),
legend.justification = c("right", "top"),
legend.box.margin = margin(1, 1, 1, 1)
)
p1
I tried using legend.key.height legend.spacing.y guide but it only stretched legend keys without adding space between them. Also how can I remove alternate lables (encircled) of Y-axis keeping tickmark with plot.
After browsing ggplot2's source code for a bit, I come to the conclusion that the legend.spacing.y is only applied when the byrow = TRUE as argument to the legend.
Simplied example below.
library(ggplot2)
ggplot(iris, aes(Sepal.Width)) +
geom_density(aes(fill = Species)) +
guides(fill = guide_legend(byrow = TRUE)) +
theme(legend.spacing.y = unit(1, "cm"))
With regards to the labels, just remove the values from the breaks argument in scale_y_continuous() that you don't want to show, you're already specifying them manually.
Hey there I'm new to R and have a very small question
I have the following dataset:
head(risk_free_rate_comparison)
Dates ` Swap rate` `Sovereign bond yield rate` `Swap rate - Sovereign bond yield rate`
<dttm> <dbl> <dbl> <dbl>
1 2007-01-02 408.9 380.9568 27.9432
2 2007-01-03 410.3 380.4535 29.8465
3 2007-01-04 409.2 381.3993 27.8007
4 2007-01-05 414.3 385.0663 29.2337
5 2007-01-08 413.1 384.2545 28.8455
6 2007-01-09 415.5 384.9770 30.5230
,with the following plot:
ggplot(d, aes(Dates, value, color = variable, linetype = variable)) +
+ geom_line() +
+ labs(color = NULL, linetype = NULL) +
+ theme_classic() +
+ theme(legend.position = "bottom") +
+ ylab("Rates in bp")
+ theme(
+ legend.position = "bottom",
+ legend.direction = "vertical",
+ legend.box.margin = margin(t = 20),
+ axis.title.x = element_text(margin = margin(t = 20)),
+ axis.title.y = element_text(margin = margin(r = 20))
+ )
Now I would like to change the line colours of the three variables to black and white style. And maybe varying line thicknesses or something in that way in order to be able to distinguish the lines.
#rbonac, see if this helps you out, and feel free to experiment by commenting out different layers or using scale_line_manual() to set your colors manually.
library(tidyverse)
mtcars %>%
mutate(cyl = factor(cyl, labels = c("4", "6", "8"))) %>%
ggplot(., aes(wt, mpg, color = cyl, linetype = cyl)) +
geom_line(size = 2) +
labs(color = NULL, linetype = NULL) +
theme_classic() +
ylab("Rates in bp") +
scale_linetype_discrete() +
scale_color_grey() +
theme(
legend.position = "bottom",
legend.direction = "vertical",
legend.box.margin = margin(t = 30),
axis.title.x = element_text(margin = margin(t = 20))
)
You can assign each variable to a line width using size aesthetic, and manually change line color and size to desired values using scale_colour_manual and scale_size_manual
ggplot(d, aes(Dates, value, color = variable)) +
geom_line(aes(linetype = variable, size=variable)) +
labs(color = NULL, linetype = NULL, size = NULL) +
theme_classic() +
theme(legend.position = "bottom") +
ylab("Rates in bp") +
scale_colour_manual(values=c("gray50", "gray25", "gray0")) +
scale_size_manual(values=c(1, 1.5, 2)) +
theme(
legend.position = "bottom",
legend.direction = "vertical",
legend.box.margin = margin(t = 20),
axis.title.x = element_text(margin = margin(t = 20)),
axis.title.y = element_text(margin = margin(r = 20))
)