如何使R的图看起来像Python的图?

bq9c1y66  于 2023-02-27  发布在  Python
关注(0)|答案(4)|浏览(113)

我试图使R上的图看起来像Python上的图:

这是Python和R的数据框架。
所有_航班_合并_月
| 年份|月份|延迟_计数|总计_计数|
| - ------|- ------|- ------|- ------|
| 二○ ○三年|一月|小行星151238|小行星552109|
| 二○ ○三年|二月|小行星158369|小行星500206|
| 二○ ○三年|马尔|小行星152156|小行星559342|
| 二○ ○三年|四月|小行星125|小行星527303|
| 二○ ○三年|五月|小行星136551|小行星533782|
| 二○ ○三年|六月|小行星163497|小行星536496|
| 二○ ○三年|七月|小行星183491|小行星558568|
| 二○ ○三年|八月|小行星178979|小行星556984|
| 二○ ○三年|九月|小行星113916|小行星527714|
| 二○ ○三年|十月|小行星131409|小行星552370|
| 二○ ○三年|十一月|小行星157157|小行星528171|
| 二○ ○三年|12月|小行星206743|小行星555495|
| 二○ ○四年|一月|小行星198818|小行星583987|
| 二○ ○四年|二月|小行星183|小行星553876|
| 二○ ○四年|马尔|小行星183273|小行星6014一二|
| 二○ ○四年|四月|小行星170114|小行星582970|
| 二○ ○四年|五月|小行星191604|小行星594457|
| 二○ ○四年|六月|小行星238|小行星588792|
| 二○ ○四年|七月|小行星237670|小行星614166|
| 二○ ○四年|八月|小行星215667|小行星623107|
| 二○ ○四年|九月|小行星147508|小行星585125|
| 二○ ○四年|十月|小行星193|小行星610037|
| 二○ ○四年|十一月|小行星1975|小行星584610|
| 二○ ○四年|12月|小行星254786|小行星606731|
| 二○ ○五年|一月|小行星229809|小行星594924|
| 二○ ○五年|二月|小行星184920|小行星545332|
| 二○ ○五年|马尔|小行星226883|小行星617540|
| 二○ ○五年|四月|小行星169221|小行星594492|
| 二○ ○五年|五月|小行星178327|小行星614802|
| 二○ ○五年|六月|小行星236724|小行星609195|
| 二○ ○五年|七月|小行星268988|小行星627961|
| 二○ ○五年|八月|小行星240410|小行星630904|
| 二○ ○五年|九月|小行星165541|小行星574253|
| 二○ ○五年|十月|小行星186778|小行星592712|
| 二○ ○五年|十一月|小行星193399|小行星566138|
| 二○ ○五年|12月|小行星256861|小行星572343|
下面是Python的代码:

# To plot the line graph
# Create separate data frames for each year
years = All_Flights_Combined_Month['Year'].unique()
data_frames_month = [All_Flights_Combined_Month[All_Flights_Combined_Month['Year'] == year] for year in years]

# Create subplots
fig, ax = plt.subplots(figsize=(10, 8))

# Plot Delay_count for each year
for i, year in enumerate(years):
    color = 'red' if str(year) == '2003' else 'green' if str(year) == '2004' else 'blue'
    ax.plot(data_frames_month[i]['Month'], data_frames_month[i]['Delay_count'], label=f"{year} Delay Count", color=color)

# Plot Total_Count for each year
for i, year in enumerate(years):
    color = 'orange' if str(year) == '2003' else 'yellow' if str(year) == '2004' else 'purple'
    ax.plot(data_frames_month[i]['Month'], data_frames_month[i]['Total_Count'], label=f"{year} Total Count", color=color)

# Set title and labels
ax.set_title('Flight Count by Month')
ax.set_xlabel('Month')
ax.set_ylabel('Number of Flights')

# Add legend
ax.legend(title='Year')

# Save the plot as a pdf file
plt.savefig('Monthly Flight Comparison Python.pdf', format='pdf')

# Show the plot
plt.show()

这是针对R的:

{r}
# To plot the line graph
month_plot <- ggplot() + geom_line(data= All_Flights_Combined_Month, aes(x =Month, y=Delay_count, group=Year, color=Year)) + 
  geom_line(data=All_Flights_Combined_Month, aes(x =Month, y=Total_count, group=Year, color=Year))+ scale_x_discrete(limits = c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"))+
  xlab("Months")+
  ylab("Number of Flights")+
  ggtitle("Flight Count by Month")

# To save the plot  as .pdf
ggplot2::ggsave("Monthly Flight Comparison R.pdf", plot = last_plot(), width = 8, height = 6)

我需要的图例和线的颜色,以配合Python的。我希望我已经提供了足够的信息。请善意的意见,谢谢。
我尝试将scale_color_manual添加到每个geom_line,但它产生了一个错误,指出scale_color_manual值已经被使用,它将覆盖以前的值。

f4t66c6m

f4t66c6m1#

这类问题通常与数据整形有关。格式应为长格式,而数据为宽格式。有关如何将数据从宽格式整形为长格式,请参阅this post
然后将变量Yearname更改为这两个变量之间的交互,这就是颜色和分组变量。

suppressPackageStartupMessages({
  library(dplyr)
  library(tidyr)
  library(ggplot2)
})

clrs <- c("2003 Delay Count" = "#e44b3b", "2003 Total Count" = "#edbe70",
          "2004 Delay Count" = "#0d720d", "2004 Total Count" = "#f8f867", 
          "2005 Delay Count" = "#0000cb", "2005 Total Count" = "#6d0469")

All_Flights_Combined_Month %>%
  pivot_longer(ends_with("count")) %>%
  mutate(Month = factor(Month, levels = month.abb),
         Year = interaction(Year, name, sep = " "),
         Year = sub("_c", " C", Year)) %>%
  select(-name) %>% 
  ggplot(aes(Month, value, colour = Year, group = Year)) +
  geom_line(linewidth = 1.25) +
  scale_color_manual(values = clrs) +
  theme_minimal()

创建于2023年2月19日,使用reprex v2.0.2

数据

x <- "Year  Month   Delay_count     Total_count
2003    Jan     151238  552109
2003    Feb     158369  500206
2003    Mar     152156  559342
2003    Apr     125699  527303
2003    May     136551  533782
2003    Jun     163497  536496
2003    Jul     183491  558568
2003    Aug     178979  556984
2003    Sep     113916  527714
2003    Oct     131409  552370
2003    Nov     157157  528171
2003    Dec     206743  555495
2004    Jan     198818  583987
2004    Feb     183658  553876
2004    Mar     183273  601412
2004    Apr     170114  582970
2004    May     191604  594457
2004    Jun     238074  588792
2004    Jul     237670  614166
2004    Aug     215667  623107
2004    Sep     147508  585125
2004    Oct     193951  610037
2004    Nov     197560  584610
2004    Dec     254786  606731
2005    Jan     229809  594924
2005    Feb     184920  545332
2005    Mar     226883  617540
2005    Apr     169221  594492
2005    May     178327  614802
2005    Jun     236724  609195
2005    Jul     268988  627961
2005    Aug     240410  630904
2005    Sep     165541  574253
2005    Oct     186778  592712
2005    Nov     193399  566138
2005    Dec     256861  572343"
All_Flights_Combined_Month <- read.table(text = x, header = TRUE)

创建于2023年2月19日,使用reprex v2.0.2

iyfamqjs

iyfamqjs2#

大概是这样的

library(tidyverse)

df %>% 
  pivot_longer(-c(Year, Month)) %>%  
  mutate(Year = paste(Year, name)) %>% 
  ggplot(aes(x =Month, y=value, color=factor(Year)))+
  geom_line(aes(group = Year))+
    scale_x_discrete(limits = c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"))+
    scale_color_manual(values = c("purple", "yellow", "gold", "blue", "green", "red"))+
  xlab("Months")+
  ylab("Number of Flights")+
  ggtitle("Flight Count by Month")+
  theme_classic()

m1m5dgzv

m1m5dgzv3#

您可以将数据转换为更长的格式,并使用paste0gsub将Year和Delay count和Total count的更长格式合并为一个字符串。要获得正确的颜色,您可以使用scale_color_manual,并使用breaks进行正确的排序,如下所示:

library(ggplot2)
library(dplyr)
library(tidyr)
df %>%
  pivot_longer(cols = Delay_count:Total_count) %>%
  mutate(Year2 = paste0(Year, " ", gsub("_", " ", name)),
         Month = factor(Month, levels = month.abb)) %>%
  ggplot(aes(x = Month, y = value, color = Year2, group = Year2)) +
  geom_line() +
  labs(color = "Year", x = "Month", y = "Number of Flights") +
  scale_color_manual(values = c("2003 Delay count" = "red", 
                                "2004 Delay count" = "green", 
                                "2005 Delay count" = "blue", 
                                "2003 Total count" = "orange", 
                                "2004 Total count" = "yellow", 
                                "2005 Total count" = "purple"),
                     breaks = c("2003 Delay count",
                                "2004 Delay count",
                                "2005 Delay count",
                                "2003 Total count", 
                                "2004 Total count", 
                                "2005 Total count"))

创建于2023年2月19日,使用reprex v2.0.2

qhhrdooz

qhhrdooz4#

首先,将reshape转换为宽格式,然后使用matplot并稍微定制axismtext

dat_w <- reshape(dat, idvar='Month', timevar='Year', direction='w')

par(mar=c(5, 6, 4, 2))
matplot(dat_w[, -1], type='l', lty=1, col=2:8, axes=FALSE, ylab='', main='Flight Count By Month')
axis(side=1, at=1:12, labels=dat_w$Month, cex.axis=.8)
axis(2, axTicks(2), formatC(axTicks(2), format='f', digits=0), las=2, cex.axis=.8)
mtext('Month', side=1, line=2.5, cex=.8); mtext('Number of Flights', 2, 4, cex=.8)
legend('right', c(paste(unique(dat$Year), rep(gsub('_', ' ', names(dat)[3:4]), each=3))),
       col=2:8, lty=1, title='Year', cex=.7)
box()

相关问题