Home > Software engineering >  How do you use ggplot2 to turn a row of numerical data into a bar chart?
How do you use ggplot2 to turn a row of numerical data into a bar chart?

Time:04-09

This is the data I'm trying to visualize:

>Name_Count
 #  A     B     C     D     E     F     G     H     I     J     K     L     M     N     O     P     Q     R     S     T     U
#  <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> #<int> <int> <int> <int> <int>
#1    23    28    45   141    18    47    42    12    27    21    49     8    50    28     3     9    15    40    94    25     5
# ... with 5 more variables: V <int>, W <int>, X <int>, Y <int>, Z <int>

This is the code I used to try and create a bar chart, but I get an error saying "Aesthetics must be either length 1 or the same as the data".

ggplot(data = Name_Count, aes(x = LETTERS, y = row(Name_Count, 1)))  
  geom_bar()

CodePudding user response:

You can do:

library(ggplot2)

ggplot(tidyr::pivot_longer(df, 1:26), aes(name, value))  
  geom_col(fill = "deepskyblue4")  
  theme_minimal()

enter image description here


Question data in reproducible format

Last 5 numbers made up as missing in OP

Name_Count <- structure(list(A = 68L, B = 39L, C = 1L, D = 34L, E = 87L, F = 43L, 
    G = 14L, H = 82L, I = 59L, J = 51L, K = 85L, L = 21L, M = 54L, 
    N = 74L, O = 7L, P = 73L, Q = 79L, R = 37L, S = 83L, T = 97L, 
    U = 44L, V = 84L, W = 33L, X = 35L, Y = 70L, Z = 96L), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -1L))

CodePudding user response:

I believe the code below is a solution to your problem.

# creating an adjusted dataframe based on Name_Count
df <- t(Name_Count)
df <- data.frame(rownames(df), df[,1])
colnames(df) <- c('Letters','Values')

# loading packages
library(ggplot2)

# plotting
ggplot(df, aes(x = Letters, y = Values))  
  geom_bar(stat='identity')
  •  Tags:  
  • r
  • Related