How to Add Axis Text in This Negative and Positive Bars Differently Using Ggplot2

How to add axis text in this negative and positive bars differently using ggplot2?

Here's a solution using dplyr to create some extra columns for the label position and the justification, and then theming the plot to match reasonably closely what you originally had:

library("dplyr")
library("ggplot2")
df <- df %>%
mutate(
genus = factor(genus, levels = genus[order(value, decreasing = TRUE)]),
label_y = ifelse(value < 0, 0.2, -0.2),
label_hjust = ifelse(value < 0, 0, 1)
)

my_plot <- ggplot(df, aes(x = genus, y = value, fill = class)) +
geom_bar(stat = "identity", col = "black") +
geom_text(aes(y = label_y, label = genus, hjust = label_hjust)) +
coord_flip() +
scale_fill_manual(values = c(groupA = "forestgreen", groupB = "goldenrod")) +
theme_minimal() +
theme(axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
axis.title.y = element_blank(),
legend.position = "top",
legend.justification = 0.05,
legend.title = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
panel.grid.major.x = element_line(colour = "grey80", linetype = "dashed"),
panel.grid.minor.x = element_blank()) +
scale_y_continuous(expression(log[10](italic("LDA score"))),
breaks = -6:6, limits = c(-6, 6))

print(my_plot)
ggsave("lefse.tiff", width = 5, height = 5, dpi = 400, my_plot)

Sample Image

Put labels over negative and positive geom_bar

Pass position of geom_text on y axis with y = Value + 2 * sign(Value)

library(ggplot2)
ggplot(dat, aes(Types, Value)) +
geom_bar(stat = "identity" ,color = "#FFFFFF" , fill = "dodgerblue3") +
geom_text(aes(y = Value + 2 * sign(Value), label = Value),
position = position_dodge(width = 0.9),
size = 3.5 , angle = 90)

Sample Image

Another plot with minor visual tweaks that I do on my plots:

As you have numbers with bars you don't need y-axis (it's redundant).

ggplot(dat, aes(Types, Value)) + 
geom_bar(stat = "identity", color = "black" , fill = "grey",
size = 0.7, width = 0.9) +
geom_text(aes(y = Value + 2 * sign(Value), label = Value),
position = position_dodge(width = 0.9),
size = 5) +
theme_classic() +
theme(axis.text.x = element_text(size = 12),
axis.title = element_text(size = 20),
axis.text.y = element_blank(),
axis.line = element_blank(),
axis.ticks = element_blank())

Sample Image

Creating a positive negative bar chart in r

Next approach can guide you to the right path:

library(ggplot2)
#Data
x5$Var <- as.character(x5$Row.names)
#Plot
ggplot(x5,aes(x=Var,y=`2020-12-08`,fill=Name))+
geom_bar(stat = 'identity')+
geom_text(aes(x=Var,y=ifelse(`2020-12-08`<0,2,-2),
label=Name),vjust=0.5)+
coord_flip()

Output:

Sample Image

customize ggplot2 axis labels with different colors

You can provide a vector of colors to the axis.text.x option of theme():

a <- ifelse(data$category == 0, "red", "blue")

ggplot(data, aes(x = x, y = y)) +
geom_bar(stat = "identity", aes(fill = category)) +
theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = a))

Sample Image

Inward facing bar labels in a bar chart with negative values with ggplot2

You should be able to set the vjust inside of the aes mappings to control differently for each row, here based on whether it is positive or negative:

ggplot(df, aes(trt, outcome, label = outcome)) +
geom_bar(stat = "identity",
position = "identity") +
geom_text(aes(vjust = outcome > 0)
, color = 'red')

Sample Image

If you want to move the labels around more precisely (instead of just vjust = 0 or vjust = 1 that you can get from a logical), you can use ifelse and define you positions more exactly:

ggplot(df, aes(trt, outcome, label = outcome)) +
geom_bar(stat = "identity",
position = "identity") +
geom_text(aes(vjust = ifelse(outcome > 0
, 1.5, -0.5) )
, color = 'red'
)

Sample Image

ggplot: How to set different alignments on the geom_text position based on type of variable?

One option to achieve your desired result would be to compute/set the positions for each label and the horizontal alignment manually instead of making use of position="fill":

Making use of some random mock data:

library(ggplot2)
library(dplyr)

dfm <- dfm %>%
group_by(Year) %>%
arrange(desc(variable)) %>%
mutate(
pct = value / sum(value),
x_label = case_when(
variable == "Marionete" ~ 0,
variable == "Pedido" ~ .5 * (cumsum(pct) + lag(cumsum(pct))),
TRUE ~ 1
),
hjust = case_when(
variable == "Marionete" ~ 0,
variable == "Pedido" ~ .5,
TRUE ~ 1
)
)

ggplot(dfm, aes(y = Year, x = abs(value), fill = variable)) +
scale_x_continuous(sec.axis = sec_axis(trans = ~ . * 1, name = "Trab."), expand = expansion(mult = c(0, 0.05))) +
geom_col(width = .7, colour = "black", lwd = 0.1, position = "fill", orientation = "y") +
geom_text(aes(x = x_label, label = format(round(value, digits = 0), nsmall = 0, decimal.mark = ",", big.mark = "."), hjust = hjust),
size = 4, color = "white"
) +
theme(
panel.grid.major = element_line(colour = "gray90", size = 0.75), panel.grid.minor = element_line(colour = "gray90", size = 0.75),
legend.position = "top", axis.text.x = element_blank(), axis.ticks.x = element_blank(),
axis.title.x = element_blank(), panel.background = element_blank()
) +
scale_fill_manual(values = c("#000000", "tomato", "blue"))

Sample Image

DATA

set.seed(123)

dfm <- data.frame(
Year = rep(c(2006:2016), each = 3),
value = sample(1:100, 3 * 11, replace = TRUE),
variable = c("Fatura", "Pedido", "Marionete")
)
dfm$variable <- factor(dfm$variable, levels = c("Fatura", "Pedido", "Marionete"))
dfm$Year <- factor(dfm$Year)

Vary colors of axis labels in R based on another variable

If you ignore the vectorised possibilities like text and mtext, you can get there by repeatedly calling axis. The overhead timewise will be very minimal and it will allow all the axis calculations to occur as they normally do. E.g.:

# original code
grid = structure(c(1:12),.Dim = c(4,3))
labs = c("A","B","C")
image(1:4,1:3,grid,axes=FALSE, xlab="", ylab = "")
axiscolors = c("black","red","black")

# new code
Map(axis, side=2, at=1:3, col.axis=axiscolors, labels=labs, lwd=0, las=1)
axis(2,at=1:3,labels=FALSE)

Resulting in:

Sample Image



Related Topics



Leave a reply



Submit