TheDeshBhakt
TheDeshBhakt

Reputation: 13

Bar chart using R

Given a csv file with two columns I want to plot bar graph to show the number of tweets posted using iPhone, mac, ipad and android in decreasing order using R. Device name is embed with text problem with remove text and plot bar graph.

data <- structure(list(Device = structure(c(1L, 1L, 2L, 
        3L, 4L, 5L), .Label = c("Twitter for iphone", "Twitter for android", "Twitter for mac", "Twitter for android", "Twitter for ipad", 
                      "Twitter for android"), class = "factor"),Text = structure(c(5L, 
        3L, 6L, 4L, 2L, 1L), .Label = c("Matches is abandoned", "Policy changes in finance", 
        "Launches of new satellites", "Premium policy get activate by company abc", 
        "Technology makes trend",
        "Weather forecasting by xyz"), class = "factor")), class = "data.frame", row.names = c(NA, 
        -6L))

I will get an error using R in plotting the bar graph using given dataset.

Upvotes: 1

Views: 261

Answers (3)

Thomas Neitmann
Thomas Neitmann

Reputation: 2722

If you want to plot the counts of tweets from each device you can use bar_chart() from the {ggcharts} package.

data$Device <- as.character(data$Device)
ggcharts::bar_chart(data, Device)

enter image description here

The resulting plot is a ggplot so you can further customize it using any {ggplot2} function.

Upvotes: 3

Harshal Gajare
Harshal Gajare

Reputation: 615

(ggplot approach) You can use below code:

library(ggplot2)
data$only_Device<-gsub(".*for ","", data$Device)
a<-table(data$only_Device) %>% as.data.frame() %>% arrange(desc(Freq))
a$Var1<-as.factor(a$Var1)
ggplot(a, aes(x = reorder(Var1, -Freq), y = Freq)) +geom_bar(stat = "identity")

enter image description here

Upvotes: 1

Jan
Jan

Reputation: 5284

Your data frame contains two factors with raw information. A bar plot requires a number per category to plot. So, you could do this.

barplot(table(data$Device))
barplot(table(data$Text))

table counts the occurrencies of the factor levels and feeds them into the bar plot.

Upvotes: 1

Related Questions