在基本R图表上绘制数据框

问题描述 投票:0回答:1

我认为这是一个基本的问题,但是我没有看到任何可以解决此问题的答案。

因此,我想将此数据框的每一行放在图表上,在x和y轴上分别具有列和行名称。

> indicador.transposta
                        31-12-2017.pdf     31-12-2018.pdf      31-12-2019.pdf
Liq..Imed.           0.260650162167045  0.278000595266861   0.100940099971038
Liq..Corr.            1.20707183817692   1.07611507200346   0.775547123687795
Liq..Seca             1.01127035774033   0.87978786315216   0.616295652990034
Liq..Geral            1.38911863440832   1.20904526839338    1.22121514777491
Endividamento        0.719880919620619  0.827098890456626   0.818856531399918
Retorno.s..Invest. -0.0281507369406506 -0.110425824989136 0.00682789312217763
Retorno.s..PL       -0.100495606734552 -0.638664640618945   0.037693289053948
Margem.Líquida     -0.0440458341645613 -0.181853784203517  0.0103531380484155

结构为:

> str(indicador.transposta)
'data.frame':   8 obs. of  3 variables:
 $ 31-12-2017.pdf: chr  "0.260650162167045" "1.20707183817692" "1.01127035774033" "1.38911863440832" ...
 $ 31-12-2018.pdf: chr  "0.278000595266861" "1.07611507200346" "0.87978786315216" "1.20904526839338" ...
 $ 31-12-2019.pdf: chr  "0.100940099971038" "0.775547123687795" "0.616295652990034" "1.22121514777491" ...

问候

r dataframe charts
1个回答
1
投票

Base R:

plot(NA, type = "n", xlim = c(1, nrow(dat)), xlab = "", ylim = range(unlist(dat)), ylab = "")
for (y in dat) lines(y)

simple base plot

但是处理不同的行,然后选择着色等,从长远来看,转换到ggplot2可能会更容易。该图形引擎更喜欢“长”格式的数据,因此我们将使用tidyr::pivot_longer对其进行整形:

library(tidyr) # pivot_longer
library(ggplot2)
pivot_longer(dat, -x)
# # A tibble: 24 x 3
#        x name            value
#  * <int> <chr>           <dbl>
#  1     1 X31.12.2017.pdf 0.261
#  2     1 X31.12.2018.pdf 0.278
#  3     1 X31.12.2019.pdf 0.101
#  4     2 X31.12.2017.pdf 1.21 
#  5     2 X31.12.2018.pdf 1.08 
#  6     2 X31.12.2019.pdf 0.776
#  7     3 X31.12.2017.pdf 1.01 
#  8     3 X31.12.2018.pdf 0.880
#  9     3 X31.12.2019.pdf 0.616
# 10     4 X31.12.2017.pdf 1.39 
# # ... with 14 more rows

ggplot(pivot_longer(dat, -x), aes(x, value, color = name, group = name)) +
  geom_line()

simple ggplot2

© www.soinside.com 2019 - 2024. All rights reserved.