我有一个数据表,我可以把它放入Excel中的聚类柱形图中。我想做同样的事情,但在R中创建图表。如何才能做到这一点?Table of DataChart in Excel
我尝试了下面的方法,结果得到了所附的图表。数据的顺序和标签不正确。ggplot在我的机器上不起作用,所以不是一个选项。
# Create a data frame with the given data
data <- data.frame(
City = c("Minneapolis", "Minneapolis", "Minneapolis", "Orlando", "Orlando", "Orlando",
"Phoenix", "Phoenix", "Phoenix", "Sacramento", "Sacramento", "Sacramento"),
Tree_Type = c("No Tree", "Medium Tree", "Large Tree", "No Tree", "Medium Tree", "Large Tree",
"No Tree", "Medium Tree", "Large Tree", "No Tree", "Medium Tree", "Large Tree"),
E_Plus = c(158, 133, 123, 879, 863, 827, 2858, 2812, 2779, 421, 363, 351),
iTE = c(1354, 1337, 1331, 6057, 6043, 6041, 4356, 4336, 4328, 2125, 2099, 2078)
)
# Set up the positions for bars
bar_width <- 0.35
barplot(
height = c(data$E_Plus, data$iTE),
beside = TRUE,
names.arg = paste(data$City, data$Tree_Type),
col = c("red", "blue"),
main = "Energy Consumption by City and Tree Type",
ylab = "Energy Consumption",
xlab = "City / Tree Type",
ylim = c(0, max(data$E_Plus, data$iTE) + 500) # Adjust the y-axis limits if necessary
)
# Adding legend
legend("topright", legend = c("EnergyPlus", "i-Tree Energy"), fill = c("red", "blue"))
# Adding data labels under the bars
text(
x = 1:(nrow(data) * 2),
y = -50, # Adjust the vertical position of the labels
labels = paste(data$City, data$Tree_Type),
xpd = TRUE,
srt = 45,
adj = c(1.2, 1.2),
cex = 0.8
)
2条答案
按热度按时间f87krz0w1#
您可以使用
barplot
的matrix
形式(即,为height
提供矩阵而不是向量-每列表示一个条形图,每行表示堆叠条形图或旁边的隐藏条形图(beside = TRUE
))。然后每个组已经很好地放在一起,组之间有一些间隙。然后你需要一些摆弄标签,你可以得到非常接近Excel正在做的事情:
字符串
x1c 0d1x的数据
eblbsuwk2#
我们可以
reshape
数据,并使用一些算法来避免硬编码(尽可能多地)。字符串
x1c 0d1x的数据
很遗憾
barplot
还没有panel.first=
参数!型