I am plotting the data with emp on the x-axis, test_ind on the y-axis, and applying coord_flip()
. The test_ind values go from 0-1 but the plot ends up showing 0-6 on the y-axis.
mydata<-structure(list(
emp = c("Cohort 95", "Cohort 95", "Cohort 95", "Cohort 95", "Cohort 71", "Cohort 71"),
department = c("Dept 2", "Dept 2", "Dept 2", "Dept 2", "Dept 2", "Dept 2"),
cat = c("MR", "DX", "CT", "US", "DX", "MR"),
n = c(941L, 387L, 365L, 341L, 330L, 322L),
dept_order_num = c(1, 1, 1, 1, 1, 1),
data_ind = c(1015L, 1015L, 1015L, 1015L, 373L, 373L),
test_ind = c(0.927093596059113, 0.38128078817734, 0.359605911330049, 0.335960591133005, 0.884718498659517, 0.863270777479893)
), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
Plot code:
library(dplyr)
library(ggplot2)
library(randomcoloR)
palette <- distinctColorPalette(length(unique(mydata$cat)))
cat_colors <- setNames(palette, sort(unique(mydata$cat)))
ggplot(mydata, aes(x = emp, y = test_ind, fill = cat)) +
geom_bar(stat = "identity", position = "stack") +
coord_flip() +
labs(
title = "test data",
x = "emp",
y = "Average",
fill = "category"
) +
scale_fill_manual(values = cat_colors) +
theme_minimal(base_size = 12) +
theme(
axis.text.y = element_text(size = 11),
axis.text.x = element_text(size = 11),
legend.position = "right",
plot.title = element_text(face = "bold", size = 15, hjust = 0.5)
)
geom_bar(stat = "identity", position = "stack")
means the geoms are stacked based on their underlying values, so the total width of the stack is the sum of the values. Can you describe more what you wanted or expected? Maybe you meant something likegeom_bar(stat = "identity", position = position_dodge2(preserve = "single"))
coord_flip()
have been unnecessary since 2020's ggplot 3.3.0. You can useggplot(mydata, aes(x = test_ind, y = emp, fill = cat))
and drop that line. In some weird cases you might need to specify theorientation
parameter in the geom, but not here.position = "identity"
is what you want. For that, you'd want to make sure your data is sorted (as it currently is) in descending order of test_ind, since lest the larger bars entirely eclipse smaller ones.