I would like to make this kind of graph (here from Our World In data ) where the line color varies by value range.
edit : adding a screenshot to make it clearer :
With plotly, I found this example but working with type = scatter and mode = markers plot and not with lines:
x <- seq(from = -2,
to = 2,
b = 0.1)
y <- sin(x)
p11 <- plot_ly() %>%
add_trace(type = "scatter",
x = ~x,
y = ~y,
mode = "markers",
marker = list(size = 10,
color = colorRampPalette(brewer.pal(10,"Spectral"))(41))) %>%
layout(title = "Multicolored sine curve",
xaxis = list(title = "x-axis"),
yaxis = list(title = "y-axis"))
p11
is there any ways to use the colorRampPalette or values range but with line (actually it's a time series)
x <- seq(from = -2,
to = 2,
b = 0.1)
y <- sin(x)
p11 <- plot_ly() %>%
add_trace(type = "scatter",
x = ~x,
y = ~y,
mode = "lines",
line = list(width = 1,
color = colorRampPalette(brewer.pal(10,"Spectral"))(41))) %>%
layout(title = "Multicolored sine curve",
xaxis = list(title = "x-axis"),
yaxis = list(title = "y-axis"))
p11
Thank you
You can, but the more points you have the better it will look. Note that I change the .1 in x, to .001.
library(plotly)
library(RColorBrewer)
x <- seq(from = -2,
to = 2,
b = 0.001)
y <- sin(x)
z = cut(x, breaks = 5, include.lowest = T)
p11 <- plot_ly() %>%
add_lines(x = ~x,
y = ~y,
color = ~z,
colors = colorRampPalette(brewer.pal(10,"Spectral"))(length(x))) %>%
layout(title = "Multicolored sine curve",
xaxis = list(title = "x-axis"),
yaxis = list(title = "y-axis"))
p11
If I change that .001 back to .1, it's a bit ugly! You can see the gaps.
Related
I want to create interactive line- and topoplot depending on menu. I figured out how to make red the line chosen in menu, but it doesn't work for topoplot marks (black circles inside topoplot). I can change it manually (cmap[][4] = RGB{N0f8}(1.0,0.0,0.0)), but how to do that interactively?
f = Figure(backgroundcolor = RGBf(0.98, 0.98, 0.98), resolution = (1500, 700))
ax = Axis(f[1:3, 1], xlabel = "Time [s]", ylabel = "Voltage amplitude [µV]")
N = 1:length(pos) #1:4
hidespines!(ax, :t, :r)
GLMakie.xlims!(-0.3, 1.2)
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
times = range(-0.3, length=size(dat_e,2), step=1 ./ 128)
lines = Dict()
for i in N
mean_trial = mean(dat_e[i,:,:],dims=2)[:,1]
line = lines!(times, mean_trial, color = "black")
lines[i] = line
end
hidedecorations!(ax, label = false, ticks = false, ticklabels = false)
topo_axis = Axis(f[2, 2], width = 178, height = 178, aspect = DataAspect())
Makie.xlims!(low = -0.2, high = 1.2)
Makie.ylims!(low = -0.2, high = 1.2)
topoMatrix = eegHeadMatrix(pos[N], (0.5, 0.5), 0.5)
cmap = Observable(collect(ColorScheme(range(colorant"black", colorant"black", length=30))))
#cmap[][4] = RGB{N0f8}(1.0,0.0,0.0)
topo = eeg_topoplot!(topo_axis, N, # averaging all trial of 30 participants on Xth msec
raw.ch_names[1:30];
positions=pos, # produced automatically from ch_names
interpolation=NullInterpolator(),
enlarge=1,
#colorrange = (0, 1), # add the 0 for the white-first color
colormap = cmap[],
label_text=false)
hidedecorations!(current_axis())
hidespines!(current_axis())
num_prev = 0
menu = Menu(f[3, 2], options = raw.ch_names[1:30], default = nothing)#, default = "second")
on(menu.selection) do selected
if selected != nothing
num = findall(x->x==menu.selection[], raw.ch_names[1:30])[]
if num_prev != 0
lines[num_prev].color = "black"
cmap[][num] = RGB{N0f8}(1.0,0.0,0.0)
end
lines[num].color = "red"
cmap[][num] = RGB{N0f8}(1.0,0.0,0.0)
num_prev = num
end
end
notify(menu.selection)
#print(cmap[])
f
We solved this by putting this string at the end of the menu.selection section:
notify(lines)
It works, because lines() automatically creates Observable.
I would like to rotate seaborn.lineplot, so height would be on the y axis and weighted PAVD would be on x.
sns.lineplot(data = df, y = "weightedPAVD", x = "# height", ci = 10, color = "darkgreen")
plt.show()
However, if I change x and y, the figure is messed up.
sns.lineplot(data = df, x = "weightedPAVD", y = "# height", ci = 10, color = "darkgreen")
plt.show()
How to fix this?
With seaborn v0.12+, add orient="y" to sort/aggregate/connect over the y variable instead of the x variable.
Hi I have a dataframe with time series on my x axis and values on my y axis.
I am using Plotly and am trying to plot a vertical line on the x axis where there my df.Alert == 1.
Currently I am using another overlay with red marker to plot it but I wish to switch to a vertical line that is restricted within by the y values of my chart. The values on the y axis should still be determined by my trace plot and not the vertical line.
Is there a way for me to do this?
My code sample is written below
Trace = go.Scatter(
name = "Values",
x = df.DateTime,
y = df.Values,
mode='markers',
text= "Unit: " + df['Unit'].astype(str),
)
Alert = go.Scatter(
name = "Alert",
x = df.DateTime,
y = df.Values.where(df.Alert == 1),
mode='markers',
line = dict(color = "red"),
text= "Unit: " + df['Unit'].astype(str),
)
layout = go.Layout(
xaxis = dict(title = "Date and Time"),
yaxis = dict(title = "Values")
)
data = [Trace, Alert]
figure = go.Figure(data = data, layout = layout)
py.iplot(figure)
You perfectly describe what you want to do... plot vline
iterate over rows in DF that are alerts fig.add_vline()
n=50
df = pd.DataFrame({"DateTime":pd.date_range("1-jan-2021", freq="15min", periods=n),
"Alert":np.random.choice([0]*10+[1], n),
"Unit":np.random.choice([0,1,2,3], n),
"Values":np.random.uniform(1,10, n)})
Trace = go.Scatter(
name = "Values",
x = df.DateTime.astype(str),
y = df.Values,
mode='markers',
text= "Unit: " + df['Unit'].astype(str),
)
layout = go.Layout(
xaxis = dict(title = "Date and Time"),
yaxis = dict(title = "Values")
)
data = [Trace]
figure = go.Figure(data = data, layout = layout)
for r in df.loc[df.Alert.astype(bool),].iterrows():
figure.add_vline(x=r[1]["DateTime"], line_width=1, line_dash="solid", line_color="red")
figure
I've been using the Seaborn library to plot box plots. In one instance, I see that the whiskers are randomly missing from one of my categorical variables.
fig, ax = plt.subplots(1, 1, figsize = (60,30))
plt.axhline(y = 0, color = 'k', linestyle = ':', linewidth = 2)
ax = sns.boxplot(x = 'Neighborhood', y = 'Price difference', data = sf_data_residuals_neighborhoods,
showfliers = False, order = list(neighborhood_order_residuals['Neighborhood']), linewidth = 5)
ax = sns.stripplot(x = 'Neighborhood', y = 'Price difference', data = sf_data_residuals_neighborhoods,
order = list(neighborhood_order_residuals['Neighborhood']), jitter = 0.25, size = 15,
linewidth = 3, edgecolor = 'black', alpha = 0.5)
# set axis properties
plt.xticks(rotation=45, fontname = 'Helvetica', fontsize = 42, ha = 'right')
plt.yticks(fontname = 'Helvetica', fontsize = 42)
plt.xlabel('San Francisco neighborhood', fontsize = 55, fontname = 'Arial', fontweight = 'bold')
plt.ylabel('Actual - predicted price ($M)', fontsize = 55, fontname = 'Arial',
fontweight = 'bold')
scale = 1000000; ax.set_ylim(-1000000, 3000000); ax.yaxis.labelpad = 25
ticks = ticker.FuncFormatter(lambda y, pos: '{0:g}'.format(y/scale))
ax.xaxis.set_tick_params(width = 3, length = 15)
ax.yaxis.set_tick_params(width = 3, length = 15)
ax.yaxis.set_major_formatter(ticks)
plt.setp(ax.spines.values(), linewidth = 3)
This produces the desired plot, but appears to leave out whiskers for the Potrero Hill category:
I've tried manually stipulating the default whis = 1.5 setting in sns.boxplot() but this does not make the missing whiskers appear.
Any idea what might be causing this?
I'm hoping to adjust the location of points and lines in a dumbbell plot to separate the bars rather than overlaying them, similar to position dodge or hjust/vjust in R.
The code below produces something close to what I'd like, but the barbells are overlayed.
urlfile <- 'https://raw.githubusercontent.com/charlottemcclintock/GenSquared/master/data.csv'
df <- read.csv(urlfile)
p <- plot_ly(df, color = I("gray80")) %>%
add_segments(x = ~mom, xend = ~daughter, y = ~country, yend = ~country, showlegend = FALSE) %>%
add_markers(x = ~mom, y = ~country, name = "Mother", color = I("purple")) %>%
add_markers(x = ~daughter, y = ~country, name = "Daughter", color = I("pink")) %>%
add_segments(x = ~dad, xend = ~son, y = ~country, yend = ~country, showlegend = FALSE) %>%
add_markers(x = ~dad, y = ~country, name = "Father", color = I("navy")) %>%
add_markers(x = ~son, y = ~country, name = "Son", color = I("blue")) %>%
layout(
title = "Gender educational disparity",
xaxis = list(title = "Mean Years of Education"),
margin = list(l = 65)
)
p
By coercing the country names to a factor, I can get the ideal spacing but I lose the country labels which I'm hoping to keep. I tried using country and numeric factor index together but plotly doesn't allow discrete and continuous scales together.
df$cnum <- as.numeric(as.factor(df$country))
p <- plot_ly(df, color = I("gray80")) %>%
add_segments(x = ~mom, xend = ~daughter, y = ~cnum+.2, yend = ~cnum+0.2, showlegend = FALSE) %>%
add_markers(x = ~mom, y = ~cnum+.2, name = "Mother", color = I("purple")) %>%
add_markers(x = ~daughter, y = ~cnum+.2, name = "Daughter", color = I("pink")) %>%
add_segments(x = ~dad, xend = ~son, y = ~cnum-.2, yend = ~cnum-.2, showlegend = FALSE) %>%
add_markers(x = ~dad, y = ~cnum-.2, name = "Father", color = I("navy")) %>%
add_markers(x = ~son, y = ~cnum-.2, name = "Son", color = I("blue")) %>%
layout(
title = "Gender educational disparity",
xaxis = list(title = "Mean Years of Education"),
margin = list(l = 65)
)
p
I would like it to look like this:
But with the country names on the y-axis.
Is there a way to adjust the vertical height relative to a discrete axis point?
Update: it's not elegant but I figured out a workaround by overwriting the y axis with a section y axis! Would still love a better answer, but this is a usable fix!
df$arb=15
plot_ly(df, color = I("gray80")) %>%
add_segments(x = ~mom, xend = ~daughter, y = ~cnum+.2, yend = ~cnum+.2, showlegend = FALSE) %>%
add_markers(x = ~mom, y = ~cnum+.2, name = "Mother", color = I("purple"), size=2) %>%
add_markers(x = ~daughter, y = ~cnum+.2, name = "Daughter", color = I("pink"), size=2) %>%
add_segments(x = ~dad, xend = ~son, y = ~cnum-.1, yend = ~cnum-.1, showlegend = FALSE) %>%
add_markers(x = ~dad, y = ~cnum-.1, name = "Father", color = I("navy"), size=2) %>%
add_markers(x = ~son, y = ~cnum-.1, name = "Son", color = I("blue"), size=2) %>%
add_markers(x = ~arb, y = ~country, name = " ", color = I("white"), yaxis = "y2") %>%
layout(
yaxis=list(title="", tickfont=list(color="white")),
yaxis2 = list(overlaying = "y", side = "left", title = ""))
)