【问题标题】:Not getting color in R charts在 R 图表中没有颜色
【发布时间】:2017-02-17 23:10:15
【问题描述】:

我正在尝试获取一些变量的基本条形图。 在运行少量代码时,我得到了所需的输出图。但对于某些人来说,输出不正确,图形是单色(灰色)。 无法弄清楚它是什么错误。我附上了第二张图的输出。 请让我知道我哪里出错了。我对 R 编程很陌生。

数据集MD长这样

State   Year        Desc        Amt
TN      2014        Won     158
OK      2015        Lost    175
WA      2013        Won     145 
OG      2015        Lost    174
IL      2014        Won     165

library(ggplot2)

#Metric for AB */
AB <- ddply(MD,c("State","Year", "Desc"),
            function (MD){data.frame(  Total_Lo=nrow(MD), Total_Amt=sum(MD$Lo_Amt), Avg_Amt=mean(MD$Lo_Amt))})  


#Loan Amount metric for States
A <-ddply(AB,c("State", "Desc"), 
          function(AB){data.frame(Number_A=sum(AB$Total_Lo),Total_Amt_A=sum(AB$Total_Amt),  Avg_Amt_A=sum(AB$Total_Amt)/sum(AB$Total_Lo))})

 #Loan Amount Metric for Years
B <-ddply(AB,c("Year" , "Desc"),
          function(AB){data.frame(Number_B=sum(AB$Total_Lo),Total_B=sum(AB$Total_Amt),Avg_B=sum(AB$Total_Amt)/sum(AB$Total_Lo))})

#Getting proper output
qplot(State, data = A, 
      fill=State, geom = "bar",  
      weight=Total_Amt_,ylab="Total Amount", 
      main = "Total  Amount for all ")

#Getting output but no color
qplot(Year, data = B, fill=_Year, 
      geom = "bar",weight=Number_B,ylab="Total Count ", 
      main = " Number by Year") 

#No proper output
qplot(State, data = AB, fill=Year, 
      geom = "bar",weight=Total_Number_Lo, 
      ylab="Total Number", main = "Number each state ")

【问题讨论】:

  • 不可重现,对象MD 丢失。使用dput(MD) 并粘贴结果
  • 我仍然无法重现最后的情节,我不得不修复一些代码。阅读有关制作 great, reproducible example in R 的信息

标签: r plot ggplot2 plyr


【解决方案1】:

您必须参考fill 美学,然后通过scale_fill_manual 为其指定颜色:

qplot(Year, data = B, fill='FILL_AES', 
      geom = "bar",weight=Number_B,ylab="Total Count ", 
      main = " Number by Year") +
  scale_fill_manual(values = c('FILL_AES' = 'blue'))

请注意,qplot 并非旨在创建完全成熟的图表,它只是用于快速原型设计和测试。如果您需要自定义图表,请使用和学习ggplot

ggplot(B, aes(x = Year, y = Number_B)) +
  geom_bar(stat = 'identity', fill = 'blue') +
  ggtitle('Number by year')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 2021-03-24
    相关资源
    最近更新 更多