使用apply(),您的表格可以转换为 2x3 矩阵,每个性别一行,每个唯一标签值一列。
然后,将新创建的矩阵提供给barplot() 内的height 参数。
# load data
df <-
read.table(
text = "hashtag Daily_Freq men women
'#a' 10 6 4
'#b' 15 5 10
'#c' 20 8 12"
, header = TRUE
, stringsAsFactors = FALSE
)
# we want three barcharts
# one for unique hashtag
# and each with two columns
# one for men and one for women
gendered.frequencies.by.hashtag <-
apply( X = df
, MARGIN = 1
, FUN = function( i )
as.numeric(
c( i[["women"]], i[["men"]] )
)
)
# name the rows
rownames( x = gendered.frequencies.by.hashtag ) <-
c( "women", "men" )
# name the columns
colnames( x = gendered.frequencies.by.hashtag ) <-
unique( df$hashtag )
# create complementary color scheme
color.scheme <- c( "#18A4D2", "#D24618" )
# plot the matrix
png(
filename = "Gendered_Freq_by_HT.png"
, res = 300
, units = "px"
, height = 1600
, width = 2800
)
barplot(
height = gendered.frequencies.by.hashtag
, names.arg = colnames( gendered.frequencies.by.hashtag )
, legend.text = TRUE
, args.legend = list(
x = "topleft"
, bty = "n"
)
, col = color.scheme
, border = NA
, beside = TRUE
, las = 1
, ylim = c( 0, max( gendered.frequencies.by.hashtag ) )
, main = "Hashtag Frequencies by Gender"
, ylab = "Frequency"
)
# shut down plot device
dev.off()
# end of script #