PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, June 27, 2022

[FIXED] How can I bar plot a dataframe with ggplot2?

 June 27, 2022     bar-chart, ggplot2, graph, r     No comments   

Issue

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?


Solution

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

enter image description here

Data

df.MontosTipo <-
  structure(
    list(`Montos totales` = c(1617682625, 248738139)),
    row.names = c("Tipo de moneda 1",
                  "Tipo de moneda 2"),
    class = "data.frame"
  )


Answered By - AndrewGB
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing