Plotting Multiple Data in a Data Frame at Fixed Column Intervals with Corresponding Legend in One Single Plot

Plotting multiple data in a data frame at fixed column intervals with corresponding legend in one single plot

Use melt to reshape your data into long format:

x4 <- melt(x3, id=c("x"), measure=c("t","s.1","z.2","y.3","x.4","q.4"), variable = "cols")

Then create your plot with:

ggplot(x4) +
geom_line(aes(x=x, y=value, color=cols), size=1) +
scale_y_continuous()

which gives:

Sample Image

Generate multiple x-y plots from the same data frame in the same plot using ggplot2 in R using a loop and display corresponding legend

You don't need a loop if you put your data into the right format. You can create a long data frame based on your original data frame.

x1_long <- data.frame(x = unlist(x1[c(TRUE, FALSE)]),
y = unlist(x1[c(FALSE, TRUE)]),
ind = gl(ncol(x1) / 2, nrow(x1)))

Now, a single geom_line command is sufficient:

library(ggplot2)
ggplot(x1_long) +
geom_line(aes(x = x, y = y, colour = ind))

Sample Image

(Note. The red line is plotted too but its values are quite small.)

Python defining xlim when when plotting multiple year data on same axis

It is still unclear what the conditions of the dataframes are but mixing pandas matplotlib convenience wrapper with higher-end matplotlib functions often creates problems. Assuming that exactly one monthly datapoint per dataframe exists, you could extract the month number and relabel the x-axis with the month name:

import pandas as pd
import matplotlib.pyplot as plt
import calendar

data15 = pd.DataFrame([1,2,3,4,5,6,7,8,9,10,11,12], index=pd.date_range(start='2015-01',end='2016-01',freq='M'), columns=['2015'])
data16 = pd.DataFrame([5,4,3,2,1], index=pd.date_range(start='2016-01',end='2016-06',freq='M'), columns=['2016'])

#generating column with month number
data15['month'] = data15.index.to_series().dt.month
data16['month'] = data16.index.to_series().dt.month

fig, ax = plt.subplots()

ax.plot(data15['month'], data15['2015'], label="2015")
ax.plot(data16['month'], data16['2016'], label="2016")

#setting x-ticks 1-12 with corresponding month names
ax.set_xticks(range(1, 13), [calendar.month_abbr[i] for i in range(1, 13)])
ax.legend()

plt.show()

Output:

Sample Image

Alternatively, you can create datetime objects that are all set to the first of the corresponding month of an arbitrary year:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

data15 = pd.DataFrame([1,2,3,4,5,6,7,8,9,10,11,12], index=pd.date_range(start='2015-01',end='2016-01',freq='M'), columns=['2015'])
data16 = pd.DataFrame([5,4,3,2,1], index=pd.date_range(start='2016-01',end='2016-06',freq='M'), columns=['2016'])

#generating datetime objects keeping only the month
#while setting day/year to arbitrary values so that the curves align
data15['month'] = data15.index + pd.offsets.DateOffset(day=1, year=2000)
data16['month'] = data16.index + pd.offsets.DateOffset(day=1, year=2000)

fig, ax = plt.subplots()

ax.plot(data15['month'], data15['2015'], label="2015")
ax.plot(data16['month'], data16['2016'], label="2016")

#formatting monthly x-axis ticks showing only the month name
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
ax.legend()

plt.show()

The output looks the same but you still have datetime objects albeit with an arbitrary year and day.

And assuming that you might want to compare many years, you could embed the first approach in a function like this:

import pandas as pd
import matplotlib.pyplot as plt
import calendar

data15 = pd.DataFrame([1,2,3,4,5,6,7,8,9,10,11,12], index=pd.date_range(start='2015-01',end='2016-01',freq='M'), columns=['2015'])
data16 = pd.DataFrame([5,4,3,2,1], index=pd.date_range(start='2016-01',end='2016-06',freq='M'), columns=['2016'])

#collecting all dataframes to plot
plot_list = [data15, data16]

fig, ax = plt.subplots()

def plot_line(df):
#this assumes that the data to plot will always be in the first column
col = df.columns[0]
ax.plot(df.index.to_series().dt.month, df[col], label=col)

for item in plot_list:
plot_line(item)

ax.set_xticks(range(1, 13), [calendar.month_abbr[i] for i in range(1, 13)])
ax.legend()

plt.show()

Any way to display data frame information besides x and y on hover with shiny/ggplot?

You can use the following code based on the plotly package:

df <- data.frame(x=c(1,2,3,4,5), y=c(6,7,8,9,10), z=c('a','b','c','d','e'))

library(ggplot2)
# Define the content and format of the tooltip in the "text" aesthetic
p <- ggplot(df, aes(x=x, y=y,
text=paste("X=",x,"<br>Y=",y,"<br>Z=",z))) +
geom_point()

library(plotly)
p <- ggplotly(p, tooltip="text")
print(p)

Sample Image

Referencing x axis variable from a melted data frame to plot using ggplot2 in R

It looks like your column names are buggered. Try this:

x4 <- melt(df, id=names(df)[1], measure=names(df)[c(2, 5, 6, 8)], variable = "cols")
colnames(x4)[1] <- "x"
plt <- ggplot(x4) +
geom_line(aes(x=x,y= value, color=cols), size=1) +
labs(x = "x", y = "y")


Related Topics



Leave a reply



Submit