Reputation: 31
So I'm trying to create a bar plot to represent two different amounts, one representing the amount of transactions made with the coin_type_1 and another to represent the transactions of coin_type_2. As of now, I have this:
montoTipo1 <- df %>%
group_by(MONEDA, Monto) %>%
filter(MONEDA=="1") %>%
data.frame() %>%
summarise(Monto_Tipo1 = sum(Monto, na.rm = TRUE))
montoTipo2 <- df %>%
group_by(MONEDA, Monto) %>%
filter(MONEDA=="2") %>%
data.frame() %>%
summarise(Monto_Tipo2 = sum(Monto, na.rm = TRUE))
nombres.MontosTipo <- c("Tipo de moneda 1","Tipo de moneda 2")
montosTipo <- c(montoTipo1[[1]], montoTipo2[[1]])
df.MontosTipo <- data.frame(row.names = nombres.MontosTipo, montosTipo) %>%
rename("Montos totales" = montosTipo)
And the output is:
df.MontosTipo
Montos totales
Tipo de moneda 1 1617682625
Tipo de moneda 2 248738139
How can I plot so in my x axis the "Tipo de moneda" data appear and the values graphed are the values I have in my dataframe?
Upvotes: 1
Views: 854
Reputation: 93
You could arrive to the same data.frame in a more simple fashion
df.MontosTipo <- df %>%
filter(MONEDA=="2" | MONEDA=="1") %>%
group_by(MONEDA, Monto) %>%
group_by(MONEDA) %>%
summarise('Montos Totales'= sum(Monto, na.rm = TRUE)) %>%
rename("Tipo de moneda" = "MONEDA")
Using your current data.frame and as you already have tidyverse
then you can run
df.MontosTipo <-
df.MontosTipo %>%
rownames_to_column("Tipo de moneda")
Then, as the Tipo de moneda
is saved in a variable, you can call it inside ggplot
to your X-axis using the aesthetics mapping.
ggplot(df.MontosTipo,
aes(x = `Tipo de moneda`, y = `Montos Totales`,
fill = factor(`Tipo de moneda`))) +
geom_col()
Final thoughts are that is sometimes easier to create variables in the form var_name
than var name
so you do not have to add tick marks when calling them inside functions. Also, geom_bar()
does not accept both X and Y aesthethics so I would rather use geom_bar()
Upvotes: 1
Reputation: 16836
As @RuiBarradas has already pointed out, you want to change the rownames into a column, which we can do with tibble::rownames_to_column
. Here, I also provide some additional options to further customize the chart. I chose a light hue to fill each bar with. I converted the scientific notation, but if you want the scientific notation along the y-axis, then you can remove the last line here (i.e., scale_y_continuous(labels = comma)
).
library(tidyverse)
require(scales)
df.MontosTipo %>%
tibble::rownames_to_column("nombres.MontosTipo") %>%
ggplot(aes(x = nombres.MontosTipo, y = `Montos totales`, fill = factor(`Montos totales`))) +
geom_col( ) +
scale_fill_hue(c = 40) +
theme_bw() +
theme(legend.position="none") +
xlab("Nombres") +
ylab("Montos Totales") +
scale_y_continuous(labels = comma)
Output
Data
df.MontosTipo <-
structure(
list(`Montos totales` = c(1617682625, 248738139)),
row.names = c("Tipo de moneda 1",
"Tipo de moneda 2"),
class = "data.frame"
)
Upvotes: 1