Why Is Stat = "Identity" Necessary in Geom_Bar in Ggplot

In ggplot2/plotly ,when I use `geom_bar(stat='identity',position='fill')`,how to change number tip to percent format

One option (and perhaps the easiest one) would be to compute your percentages manually instead of making use of position = "fill" and create the tooltip manually via the text aesthetic which makes it easy to style the numbers, ... as you like:

library(plotly)

test_data <- data.frame(
category = c("A", "B", "A", "B"),
sub_category = c("a1", "b1", "a2", "b2"),
sales = c(1, 2, 4, 5)
)

test_data <- test_data %>%
group_by(category) %>%
mutate(pct = sales / sum(sales))

p <- test_data %>%
ggplot(aes(x = category, y = pct, fill = sub_category)) +
geom_col(aes(text = paste0(
"category: ", category, "<br>",
"sub_category: ", sub_category, "<br>",
"sales: ", scales::percent(pct)
)))

ggplotly(p, tooltip = "text")

Sample Image

ggplot2: incorrect values on y-axis when using bar plot and stat = 'identity'

stat = "identity" means use the numbers exactly as they are - not "add them up".

In a simpler plot stat = "identity" numbers are added up by the default position = "stack", but it is the stacking that effectively adds the observations. When you override the default with position = "dodge", the bars are no longer stacked so no addition takes place.

Summarizing the data as you do with dplyr is a good way to achieve your goal. Another option is geom_bar(stat = "summary", position = "dodge", fun = sum) (thanks to @teunbrand in comments).

(If you stick with stat = "identity" you may want to switch to geom_col, which is the same as geom_bar but with stat = "identity" as the default.)

My bar chart only prints a single bar from my data

You need to specify both x and y variables. x should be Continent and y should be mn. You don't quote the column names.

Also when using geom_bar() you need to specify how the values should be aggregated - in your case geom_bar(stat = "identity"). You can avoid that by using geom_col().

ggplot(life_bar, aes(x = Continent, y = mn)) + 
geom_col()

There's lots of built-in help in R e.g. ?geom_bar and extensive online help too.



Related Topics



Leave a reply



Submit