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")
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
How to Solve Prcomp.Default(): Cannot Rescale a Constant/Zero Column to Unit Variance
Is There an R Markdown Equivalent to \Sexpr{} in Sweave
How to Get Parameters from Config File in R Script
Increase Plot Size (Width) in Ggplot2
Filter One Selectinput Based on Selection from Another Selectinput
R How to Read a File from Google Drive Using R
Ggplot2: Geom_Text Resize with the Plot and Force/Fit Text Within Geom_Bar
Keep Document Id with R Corpus
Change Internal Function of a Package
Sum Nlayers of a Rasterstack in R
Data.Table Alternative for Dplyr Case_When
Multiple Strings with Str_Detect R
R: Text Progress Bar in for Loop
How to Create a Raster from a Data Frame in R
Arrange Plots in a Layout Which Cannot Be Achieved by 'Par(Mfrow ='
Rollmean with Dplyr and Magrittr