cplus
cplus

Reputation: 1115

r barplot descending order with matrix data with one column

I have a matrix data:

data <- prop.table(df,2)*100

   [,1]
FR 63.60582
US 15.90146
DE 10.07839
UK 10.41433

I do a barplot of it:

barplot(data ,beside=TRUE,legend.text=T,
        ylim=c(0,100),ylab="Percentages",
        args.legend = list(x ='topright', bty='n', inset=c(-0.5,0)))

it is not ordered descending, so I try to order it like:

data <- data [order(data $V1),]

and I get:

Error in data$V1 : $ operator is invalid for atomic vectors

so I try to convert to dataframe:

data <- as.data.frame(data)

and then do a barplot with it, but I get:

Error in barplot.default(data, beside = TRUE, legend.text = T, ylim = c(0,  : 
  'height' must be a vector or a matrix

I have the impression that I am stuck in a vicious circle here. Could somebody get me out of this chaos? thanks.

update:

dput(data) gives me:

structure(c(63.6058230683091, 15.9014557670773, 10.0783874580067, 
10.4143337066069), .Dim = c(4L, 1L), .Dimnames = list(c("FR", 
"US", "DE", "UK"), NULL))

Upvotes: 1

Views: 1625

Answers (1)

Mike H.
Mike H.

Reputation: 14360

The reason you are getting Error in data$V1 : $ operator is invalid for atomic vectors is because you can't use the $ operator for matrices. If you wanted to order by a specific column, you could do: data[order(data[,1]),] - this would order by the first column. It also works with character vectors too.

To answer your question with the data you posted this should work:

barplot(data[order(data[,1]),] ,beside=TRUE,legend.text=T,
        ylim=c(0,100),ylab="Percentages",
        args.legend = list(x ='topright', bty='n', inset=c(-0.5,0)))

enter image description here

Upvotes: 1

Related Questions