0

I am learning visualisation in R and have been facing some issues trying to make a categorical bar graph from data that I extracted from a .xlsx file in R.

The input had numerous columns and I created a dataframe with the two columns i needed for the graph. When i run the following in R, I get the error

"Error in sort.list(y) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?"

This is my script:

df<-read_excel("C:\\..\\excel.xlsx", sheet="Sheet1")
unique_df<-unique(mis[c("Vegetables", "Fruits")])

ggplot(data = unique_df, mapping = aes(x = as.factor(unique_df["Vegetables"]),
y = unique_df["Fruits"])) + geom_bar(stat = "identity") +
labs(x = "Vegetables", y="Fruits", title="Number of Codes", subtitle="Vegetables wise number of fruits")

This is similar to the dataframe (unique_df) that I need to make the visualisation from:

x             y
Red           Mango
Red           Apple
Red           Banana
Blue          Mango
Blue          Banana
Blue          Banana
Blue          Apple
Yellow        Pineapple
Green         Mango
Yellow        Pineapple
Yellow        Pineapple
Green         Apple

Output of str(unique_df)

Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   219 obs. of  2 variables:
x: chr "Red" "Red" "Red" "Blue" "Blue"...
y: chr "Mango" "Apple" "Banana" "Mango"...
  • Inside `aes` you typically only want unquoted variable names, not subsetting. For the provided data, maybe `ggplot(df, aes(x, fill = y)) + geom_bar()` – alistaire Sep 04 '18 at 06:53
  • @alistaire if i don't subset (i.e. use double quotes) then i get the error `"Error: unexpected symbol in "ggplot(data =..."` Output of "colnames(unique_df) is `[1] "Vegetables" "Fruits"` – Pranav Seth Sep 04 '18 at 07:01
  • You need to make your example [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – alistaire Sep 04 '18 at 07:03
  • Could i be facing issue with making a count of "Fruits" "Vegetable" wise because of text type column names? Output of `colname(unique_df)` is `[1] "Vegetables" "Fruits"` – Pranav Seth Sep 04 '18 at 07:09
  • 1
    No, names don't have types in R. You need to make your example reproducible. If answerers can't cause the same error, this question is not answerable. – alistaire Sep 04 '18 at 07:12

1 Answers1

0

Assume df -- data frame and "a" and "b are columns. Try below codes--and image of plot attached. ggplot(data = df,aes(x=df$a,fill=df$b))+geom_bar() enter image description here

alistaire
  • 42,459
  • 4
  • 77
  • 117
shyamrag cp
  • 102
  • 9