3

キーワードの相対頻度を伝えるために、プロット内の各「バー」が、その頻度で垂直方向に繰り返される単語の 1 つからなるようにしたいと思います。以下のggplotコードはバーのアウトラインと塗りつぶしを削除しますが、単語の頻度に応じてバーとして (またはバー内に) 単語の「スタック」を作成するにはどうすればよいですか? したがって、「グローバル」は x 軸から始まり、「グローバル」を垂直方向に 3 回繰り返し、y 軸の 1、2、3 に対して配置します。「ローカル」は 5 回スタックします。

# a toy data frame
words <- c("global", "local", "firm")
freq <- c(3, 5, 6)
df <-data.frame(cbind(words, freq))

library("ggthemes")
# a very unimpressive and uninformative plot
ggplot(df, aes(x = words, y = freq)) +
  geom_bar(stat = "identity", fill = "transparent", colour = "white") +
  theme_tufte()

ここに画像の説明を入力

textGrobで使用しようとしannotation_custom()ましたが、その頻度で単語を繰り返す方法がわかりませんでした。

ご指導ありがとうございます。

4

1 に答える 1

1

これはあなたのニーズを満たすかもしれない簡単なハックです(ただし、これを行うためのより良い方法があるに違いありません):

library(dplyr) 

# Data frame with each word appearing a number of times equal to its frequency
df.freq = data.frame(words=rep(words, freq))

# Add a counter from 1 to freq for each word. 
# This will become the `y` value in the graph.
df.freq = df.freq %>% 
  group_by(words) %>%
  mutate(counter=1:n())

# Graph the words as if they were points in a scatterplot
p1 = ggplot(df.freq, aes(words, counter-0.5)) +
  geom_text(aes(label=words), size=12) +
  scale_y_continuous(limits=c(0,max(df.freq$counter))) +
  labs(x="Words",y="Freq") +
  theme_tufte(base_size=20) + 
  theme(axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

# Save the plot, adjusting the aspect ratio so that the words stack nicely
# without large gaps between each copy of the word
pdf("word stack.pdf", 6,3.5)
p1
dev.off()

pngSOはPDFファイルを表示しないため、これがバージョンです。

ここに画像の説明を入力

単語のスタックを使用することに慣れていない場合は、別のオプションとして棒グラフを使用し、各棒の中央に単語を追加することもできます。例えば:

# a toy data frame
words <- c("global", "local", "firm")
freq <- c(3, 5, 6)
df <-data.frame(words, freq)

ggplot(df, aes(words, freq)) +
  geom_bar(stat="identity", fill=hcl(195,100,65)) +
  geom_text(aes(label=words, y=freq*0.5), colour="white", size=10) +
  theme_tufte(base_size=20) + 
  theme(axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

ここに画像の説明を入力

于 2015-03-08T20:20:11.963 に答える