logo
Tags down

shadow

Plot time series with years in different columns


By : Guillaume Blain
Date : September 16 2020, 11:00 PM
Does that help You need to convert your data from wide to long and then use ggplot. Look below;
code :
library(tidyverse)

dt %>% 
  pivot_longer(., -Team, values_to = "W", names_to = "Year") %>% 
  mutate(Year = as.integer(gsub("W", "20", Year))) %>% 
  ggplot(., aes(x=Year, y=W, group=Team)) +
  geom_line(aes(color=Team))
dt <- structure(list(Team = c("AC", "AF", "AK", "AL", "AA&M", "Alst", "Alb"), 
                     W15 = c(7L, 12L, 20L, 18L, 8L, 17L, 24L), 
                     W16 = c(9L, 12L, 25L, 18L, 10L, 12L, 23L), 
                     W17 = c(13L, 12L, 27L, 19L, 2L, 8L, 21L), 
                     W18 = c(16L, 12L, 14L, 20L, 3L, 8L, 22L), 
                     W19 = c(27L, 14L, 17L, 18L, 5L, 12L, 12L)), 
                class = "data.frame", row.names = c(NA, -7L))
#   Team W15 W16 W17 W18 W19
# 1   AC   7   9  13  16  27
# 2   AF  12  12  12  12  14
# 3   AK  20  25  27  14  17
# 4   AL  18  18  19  20  18
# 5 AA&M   8  10   2   3   5
# 6 Alst  17  12   8   8  12
# 7  Alb  24  23  21  22  12


Share : facebook icon twitter icon

Monthly time series plot with years on x-axis in R


By : aarondelani
Date : March 29 2020, 07:55 AM
around this issue First, create a time series object! (using ts())
Then plot, I guess R will show only years on X-axis automatically!
code :
#make Time to time series object
a<-ts(rnorm(150),start=c(2002,7),freq=12);a
plot(a, type="l", lwd=2, col="red", ylab= "% return",xlim=c(2002,2014),axes=F)
axis(1,at=2002:2014,labels=2002:2014);axis(2);box()

Dates with month and day in time series plot in ggplot2 with facet for years


By : user3570675
Date : March 29 2020, 07:55 AM
This might help you You are very close. You want the x-axis to be a measure of where in the year you are, but you have it as a character vector and so are getting every single point labelled. If you instead make a continuous variable represent this, you could have better results. One continuous variable would be the day of the year.
code :
df$DayOfYear <- as.numeric(format(df$Date, "%j"))
ggplot(data = df,
       mapping = aes(x = DayOfYear, y = Y, shape = Year, colour = Year)) +
  geom_point() +
  geom_line() +
  facet_grid(facets = Year ~ .) +
  theme_bw()
ggplot(data = df,
       mapping = aes(x = DayOfYear, y = Y, shape = Year, colour = Year)) +
  geom_point() +
  geom_line() +
  facet_grid(facets = Year ~ .) +
  scale_x_continuous(labels = function(x) format(as.Date(as.character(x), "%j"), "%d-%b")) +
  theme_bw()
df$CommonDate <- as.Date(paste0("2000-",format(df$Date, "%j")), "%Y-%j")
ggplot(data = df,
       mapping = aes(x = CommonDate, y = Y, shape = Year, colour = Year)) +
  geom_point() +
  geom_line() +
  facet_grid(facets = Year ~ .) +
  scale_x_date(labels = function(x) format(x, "%d-%b")) +
  theme_bw()

Pandas-Add missing years in time series data with duplicate years


By : Santosh Acharya
Date : March 29 2020, 07:55 AM
wish of those help I have a dataset like this where data for some years are missing . , Make a MultiIndex so you don't have duplicates:
code :
df.set_index(['County', 'Year'], inplace=True)
index = pd.MultiIndex.from_product(df.index.levels)
df.reindex(index)

Superposing Pandas time series from different years in Seaborn plot


By : alex
Date : March 29 2020, 07:55 AM
around this issue I have a Pandas data frame, and I want to explore the periodicity, trend, etc of the time series. Here is the data. , Setup
This parses the data that you linked
code :
df = pd.read_csv(
    'data.csv', sep=';', decimal=',',
    usecols=['date', 'speed', 'height', 'width'],
    index_col=0,  parse_dates=[0]
)
idx = pd.MultiIndex.from_arrays([
        pd.to_datetime(df.index.strftime('2012-%m-%d %H:%M:%S')),
        df.index.year
    ])

ax = df.set_index(idx).unstack().speed.plot()
lg = ax.legend(bbox_to_anchor=(1.05, 1), loc=2, ncol=2)
fig, axes = plt.subplots(3, 1, figsize=(15, 9))

idx = pd.MultiIndex.from_arrays([
        pd.to_datetime(df.index.strftime('2012-%m-%d %H:%M:%S')),
        df.index.year
    ])

d1 = df.set_index(idx).unstack().resample('W').mean()
d1.speed.plot(ax=axes[0], title='speed')
lg = axes[0].legend(bbox_to_anchor=(1.02, 1), loc=2, ncol=1)

d1.height.plot(ax=axes[1], title='height', legend=False)
d1.width.plot(ax=axes[2], title='width', legend=False)

fig.tight_layout()

R : Bar plot for time series of data corresponding to 12 months of 15 years


By : user2232782
Date : March 29 2020, 07:55 AM
around this issue I have a dataset which looks like this one below. , An alternative could be to use geom_col and facet by year.
code :
library(data.table) # for melt
library(ggplot2)

# Took the data example from @Istrel
set.seed(2018)
df <- data.frame(month = 1:12, matrix(abs(rnorm(12 * 15)), nrow = 12))
colnames(df) <- c("month", "Yi", paste0("Yi+", 1:14))
setDT(df) # just to be sure, convert to data.table; use setDF(df) to switch back
df_m <- data.table::melt(df, "month")

ggplot(data = df_m,
       aes(x = month, 
           y = abs(value),
           fill = as.factor(month))) +
  geom_col() +
  facet_grid(cols = vars(variable),
             space = "free_x",
             scales = "free_x",
             switch = "x") +
  # Some graph adjustments:
  scale_y_continuous(expand = c(0, 0)) +  # remove space between plot area and x axis
  labs(x = "Year", y = "Climate variable") +
  scale_fill_discrete(name = "Months") + # legend title
  theme(
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    panel.grid = element_blank(),
    panel.spacing = unit(0.1, "cm")  # adjust spacing between facets
  )
Related Posts Related Posts :
  • R Loop Regressions
  • kableExtra : add a footnote to a rowname [kableExtra, Rmd]
  • Find Anti-derivative in R
  • How can I install a package in "developer mode" in R / RStudio?
  • Sum two values separated by a comma in r
  • Basic mean calculation
  • how refill a column with the help of 2 other column?
  • Creating group dummy variable
  • Conditional Filtering using R
  • How do i left join 2 different tables based on license plate number and time?
  • What is a typical use case of iterative solvers for linear systems in R?
  • Best way to ggplot time series with multiple categorical values
  • Is it possible to assign specific names to data sets by looping and using the assign() function in R?
  • Removing elements in R vector to correspond with NAs in another R vector
  • how can I make set of accumulatively increasing integers in R?
  • r markdown vitae package "Undefined control sequence" error when knitting to vitae predefined cv templates
  • How can I shorten this vector without having to type in every single element?
  • How can I fill NA values in a ggplot geom_map with zigzags or oblique lines?
  • Merge two data frames by nearest date and ID
  • Issue with Density Plot using GGPLOT2
  • R convert data table to vector in reverse order
  • Generate data array from a vector of counts
  • How to unite 2 columns with all non-unique or NA values, without dropping cases (keep NA, merge duplicates) in R
  • Left join without duplicating same columns
  • Reshape row into column of the 2d array in a matrix in R
  • count the number of fluctuations between 0 and 1
  • How to modify a dataframe that can't be called directly?
  • How to make a timespan column based on a time stamp column?
  • Count or the Number of Columns That Meet Some Criteria
  • How to summarise unique values in columns of a dataframe by multiple nested blocks in R
  • if statement to assign values to dataframe on the basis of other values in the dataframe
  • Draw same random numbers with Stata and R
  • Use pipes in R to set data
  • What is the difference between new() and setClass() in R?
  • If-else statement inside apply function R
  • when I use group_by in r, it doesn't group_by the column names
  • function for iterating occurrences of a timestamp in a column by day
  • facet_zoom() while setting axis limits
  • Calculating moving average in R
  • Joining dataframes with different dimensions and filling the gaps
  • R Automatically name results of Loop
  • How to store output of a loop when resampling of parameter values for simultaneous equations in R?
  • gganimate plot where points stay and line fades
  • Find number of variables on different levels within a dataframe using dplyr?
  • Get variable names from an lm object without segregating factor levels
  • R: Using contains function while filtering
  • Use docker multistage builds for R development and deployment setting
  • Memory profiling with data.table
  • Create summary of proportions within a loop dplyr
  • Usage of make.unique for sample IDs
  • How to replicate a String in a dataframe individually N times
  • How can I remove a word before and after a particular word?
  • Legend and multiple geom_line
  • rJava load failed in R/Rstudio after upgrading to OSX Catalina
  • How do I generate the slope of a regression function with a 90% confidence interval in R?
  • Second order polynomials and linear prediction in R
  • Calculate row on datatable based on info from another data.table
  • Match row and column, then subtracting a value
  • How do I filter .csv file before reading
  • Is there a way to move labels up on a sieve plot in order to make the graphs look cleaner?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk