在同一颜色下绘制图表

3

我正在使用R中的plotly。我试图绘制具有相同颜色的图表。下面您可以看到数据和图表。

library(plotly)
library(reshape2)
library(dplyr)

df<-data.frame(city=c("NYC","Seattle","Boston","LA","Seattle"),
               value=c(100,200,300,400,500))
df <-melt(df)

现在我正在绘制饼图,颜色如下所示:
fig<-df %>% 
  plot_ly(labels = ~city, values = ~value)
fig <- fig %>% add_pie(hole = 0.6)
fig

enter image description here

最后,我想用与上面饼图相同的颜色绘制一个条形图。为此,我尝试了以下命令行:
df <-melt(df)
fig <- plot_ly(df, x = ~city, y = ~value, type = 'bar')
fig

enter image description here

有人能帮我解决如何用与饼图相同的颜色绘制条形图吗?

3个回答

1
您可以使用ggplot2包制作图表,它会为每个图表中的city提供匹配的颜色。
#install.packages('ggplot2')
library(ggplot2)
library(dplyr)

#your data frame
df<-data.frame(city=c("NYC","Seattle","Boston","LA","Seattle"),
value=c(100,200,300,400,500))
df <-melt(df)


PieChart <- df %>% ggplot(aes(x="", y=value, fill=city)) + 
  geom_bar(stat = "identity", width=1) + 
  coord_polar("y",start=0) + 
  theme_void() 
PieChart

结果图表如下: enter image description here
BarChart <- df %>% ggplot(aes(x=city, y=value, fill=city)) + 
  geom_bar(stat = "identity") +
  theme_void() + 
  xlab("City") + ylab("Value")
BarChart

生成的图表: 这里输入图片描述

我更喜欢使用Plotly及其解决方案,因为这个库与我的工作兼容。 - silent_hunter

1
你可能会发现这个链接有用。
此外,如果你想完全使用plotly,以下是你可以做的。
#install.packages('RColorBrewer')
library(RColorBrewer)
library(dplyr)
library(plotly)

df<-data.frame(city=c("NYC","Seattle","Boston","LA","Seattle"),
               value=c(100,200,300,400,500))
df <-melt(df)
df
#define a vector with colour palette of four colours
cols <- brewer.pal(12, "Set3")[1:4]
cols

柱形图:

BarChart <- df %>% plot_ly(x = ~city, y = ~value, showlegend = TRUE, 
type = 'bar', color = ~city, colors = cols)

BarChart

生成的图表: enter image description here

饼图:

PieChart <- df %>% plot_ly(labels = ~city, values = ~value, 
    marker = list(colors = cols), showlegend = TRUE) %>% 
    add_pie(hole = 0.6)
PieChart

生成的图表如下: enter image description here 请注意,这仍会为城市提供不同的颜色,因此除了上面链接的答案之外,我还建议尝试创建一个新的数据框,其中包含唯一的四个城市即没有重复项,重复城市的值求和,并绑定另一列,该列具有每个城市的唯一颜色。

1
这里有一个有点巧妙但有效的解决方案:
fig <- ggplot(df, aes(city, value, fill = city)) + 
       geom_col() +
       scale_fill_manual(values = c("#2ca02c", "#ff7f0e", 
                                    "#d62728", "#1f77b4")) +
       theme_minimal() +
       theme(panel.grid.major.x = element_blank())

ggplotly(fig)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接