Related
How to add two sets of arrows with different colours, please? I obtained just green arrows. Are red arrows overplotted? How to suppress that?
When I comment the part between ###, I have red arrows.
The desired result is to have both arrows - red and green.
Thank you
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
d = {'a': [1, 2, 2], 'b': [3, 5, 4], 'c': [0.1, 0.2, 0.6]}
df = pd.DataFrame(data=d)
fig = px.scatter(df, x='a', y='b', error_y='c')
fig.update_xaxes(title_font_family="Trebuchet")
fig.update_layout(yaxis=dict(scaleanchor="x", scaleratio=1),
template = "plotly_white",
title="<b>V</b>",
)
fig.update_layout(xaxis = dict(autorange="reversed"))
x_end = [1, 2, 2]
y_end = [3, 5, 4]
x_start = [0, 1, 3]
y_start = [4, 4, 4]
list_of_all_arrows = []
for x0,y0,x1,y1 in zip(x_end, y_end, x_start, y_start):
arrow = go.layout.Annotation(dict(
x=x0,
y=y0,
xref="x", yref="y",
text="",
showarrow=True,
axref="x", ayref='y',
ax=x1,
ay=y1,
arrowhead=3,
arrowwidth=1.5,
arrowcolor='rgb(255,51,0)',)
)
list_of_all_arrows.append(arrow)
fig.update_layout(annotations=list_of_all_arrows)
###
list_of_all_arrows2 = []
for x0,y0,x1,y1 in zip([i-2 for i in x_end], [i-3 for i in y_end], x_start, y_start):
arrow = go.layout.Annotation(dict(
x=x0,
y=y0,
xref="x", yref="y",
text="",
showarrow=True,
axref="x", ayref='y',
ax=x1,
ay=y1,
arrowhead=3,
arrowwidth=1.5,
arrowcolor='green',)
)
list_of_all_arrows2.append(arrow)
fig.update_layout(annotations=list_of_all_arrows2)
###
# fig.write_html("Fig.html")
fig.show()
The origin of the problem is that in the background figures in plotly are dictionaries. The fact that you are calling two times fig.update_layout(annotations=list_anotation) updates figure's dictionary annotations entry. To check the dictionary of a figure just print the figure print(fig), there you can see the key layout and sub key annotations.
Therefore only calling one the function update_layout works as you want.
Step1: delete this line
fig.update_layout(annotations=list_of_all_arrows) # delete this line
Step2: change last line
fig.update_layout(annotations=list_of_all_arrows2 + list_of_all_arrows)
this is equivalent to appending all arrows to a single list
Total code
import plotly.express as px
import numpy as np
import pandas as pd
import plotly.graph_objects as go
d = {'a': [1, 2, 2], 'b': [3, 5, 4], 'c': [0.1, 0.2, 0.6]}
df = pd.DataFrame(data=d)
fig = px.scatter(df, x='a', y='b', error_y='c')
fig.update_xaxes(title_font_family="Trebuchet")
fig.update_layout(yaxis=dict(scaleanchor="x", scaleratio=1),
template = "plotly_white",
title="<b>V</b>",
)
fig.update_layout(xaxis = dict(autorange="reversed"))
x_end = [1, 2, 2]
y_end = [3, 5, 4]
x_start = [0, 1, 3]
y_start = [4, 4, 4]
list_of_all_arrows = []
for x0,y0,x1,y1 in zip(x_end, y_end, x_start, y_start):
arrow = go.layout.Annotation(dict(
x=x0,
y=y0,
xref="x", yref="y",
text="",
showarrow=True,
axref="x", ayref='y',
ax=x1,
ay=y1,
arrowhead=3,
arrowwidth=1.5,
arrowcolor='rgb(255,51,0)',)
)
list_of_all_arrows.append(arrow)
list_of_all_arrows2 = []
for x0,y0,x1,y1 in zip([i-2 for i in x_end], [i-3 for i in y_end], x_start, y_start):
arrow = go.layout.Annotation(dict(
x=x0,
y=y0,
xref="x", yref="y",
text="",
showarrow=True,
axref="x", ayref='y',
ax=x1,
ay=y1,
arrowhead=3,
arrowwidth=1.5,
arrowcolor='green',)
)
list_of_all_arrows2.append(arrow)
fig.update_layout(annotations=list_of_all_arrows2 + list_of_all_arrows)
The final plot
I've generated a network figure using vedo library and I'm trying to add this as an inset to a figure generated in matplotlib
import networkx as nx
import matplotlib.pyplot as plt
from vedo import *
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
G = nx.gnm_random_graph(n=10, m=15, seed=1)
nxpos = nx.spring_layout(G, dim=3, seed=1)
nxpts = [nxpos[pt] for pt in sorted(nxpos)]
nx_lines = [(nxpts[i], nxpts[j]) for i, j in G.edges()]
pts = Points(nxpts, r=12)
edg = Lines(nx_lines).lw(2)
# node values
values = [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[30, 80, 10, 79, 70, 60, 75, 78, 65, 10],
[1, .30, .10, .79, .70, .60, .75, .78, .65, .90]]
time = [0.0, 0.1, 0.2] # in seconds
vplt = Plotter(N=1)
pts1 = pts.cmap('Blues', values[0])
vplt.show(
pts1, edg,
axes=False,
bg='white',
at=0,
interactive=False,
zoom=1.5
).screenshot("network.png")
ax = plt.subplot(111)
ax.plot(
[1, 2, 3], [1, 2, 3],
'go-',
label='line 1',
linewidth=2
)
arr_img = vplt.screenshot(returnNumpy=True, scale=1)
im = OffsetImage(arr_img, zoom=0.25)
ab = AnnotationBbox(im, (1, 0), xycoords='axes fraction', box_alignment=(1.1, -0.1), frameon=False)
ax.add_artist(ab)
plt.show()
ax.figure.savefig(
"output.svg",
transparent=True,
dpi=600,
bbox_inches="tight"
)
There resolution of the image in the inset is too low. Suggestions on how to add the inset without loss of resolution will be really helpful.
EDIT:
The answer posted below works for adding a 2D network, but I am still looking for ways that will be useful for adding a 3D network in the inset.
I am not familiar with vedo but the general procedure would be to create an inset_axis and plot the image with imshow. However, your code is using networkx which has matplotlib bindings and you can directly do this without vedo
EDIT: code edited for 3d plotting
import networkx as nx
import matplotlib.pyplot as plt
G = nx.gnm_random_graph(n=10, m=15, seed=1)
nxpos = nx.spring_layout(G, dim=3, seed=1)
nxpts = [nxpos[pt] for pt in sorted(nxpos)]
nx_lines = [(nxpts[i], nxpts[j]) for i, j in G.edges()]
# node values
values = [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[30, 80, 10, 79, 70, 60, 75, 78, 65, 10],
[1, .30, .10, .79, .70, .60, .75, .78, .65, .90]]
time = [0.0, 0.1, 0.2] # in seconds
fig, ax = plt.subplots()
ax.plot(
[1, 2, 3], [1, 2, 3],
'go-',
label='line 1',
linewidth=2
)
from mpl_toolkits.mplot3d import (Axes3D)
from matplotlib.transforms import Bbox
rect = [.6, 0, .5, .5]
bbox = Bbox.from_bounds(*rect)
inax = fig.add_axes(bbox, projection = '3d')
# inax = add_inset_axes(,
# ax_target = ax,
# fig = fig, projection = '3d')
# inax.axis('off')
# set angle
angle = 25
inax.view_init(10, angle)
# hide axes, make transparent
# inax.set_facecolor('none')
# inax.grid('off')
import numpy as np
# plot 3d
seen = set()
for i, j in G.edges():
x = np.stack((nxpos[i], nxpos[j]))
inax.plot(*x.T, color = 'k')
if i not in seen:
inax.scatter(*x[0], color = 'skyblue')
seen.add(i)
if j not in seen:
inax.scatter(*x[1], color = "skyblue")
seen.add(j)
fig.show()
I want heatmap annotation as symbols. '*' at place of 1 and blank at 0.
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
x = pd.DataFrame({'a':[1,0,1,0]})
fig, (ax) = plt.subplots(ncols=1)
sns.heatmap(x, cmap="BuPu",annot=True,fmt='g',annot_kws={'size':10},ax=ax, yticklabels=[], cbar=False, linewidths=.5,robust=True, vmin=0, vmax=1)
plt.show()
The heatmap can only annotate with numbers. To put other text (or unicode symbols), ax.text can be used. The center of each cell is at 0.5 added to both the row and the column number.
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
x = pd.DataFrame({'a': [1, 0, 1, 0], 'b': [1, 1, 0, 1], 'c': [0, 1, 0, 0]})
fig, (ax) = plt.subplots(ncols=1)
sns.heatmap(x, cmap="BuPu", annot=False, ax=ax, yticklabels=[], cbar=False, linewidths=.5)
for i, c in enumerate(x.columns):
for j, v in enumerate(x[c]):
if v == 1:
ax.text(i + 0.5, j + 0.5, '★', color='gold', size=20, ha='center', va='center')
plt.show()
I want to specify manually the color of a line segment in holoviews, based on a third column.
I'm aware of the hv.Path examples, however, this reduces the length of the line with 1 segment, which I don't want.
I can do it using bokeh, or using matplotlib, but I can't get it right using holoviews
def get_color(min_val, max_val, val, palette):
return palette[(int((val-min_val)*((len(palette)-1)/(max_val-min_val))+.5))]
from bokeh.io import output_file, show
from bokeh.plotting import figure
y = [0,1,2,3,4,5]
x = [0]*len(y)
z = [1,2,3,4,5]
p = figure(plot_width=500, plot_height=200, tools='')
[p.line([x[i],x[i+1]],[y[i],y[i+1]],line_color = get_color(1,5,z,Viridis256), line_width=4) for i,z in enumerate(z) ]
show(p)
import numpy
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
# The line format you curently have:
lines = [[(0, 1, 2, 3, 4), (4, 5, 6, 7, 8)],
[(0, 1, 2, 3, 4), (0, 1, 2, 3, 4)],
[(0, 1, 2, 3, 4), (8, 7, 6, 5, 4)],
[(4, 5, 6, 7, 8), (0, 1, 2, 3, 4)]]
# Reformat it to what `LineCollection` expects:
lines = [zip(x, y) for x, y in lines]
z = np.array([0.1, 9.4, 3.8, 2.0])
fig, ax = plt.subplots()
lines = LineCollection(lines, array=z, cmap=plt.cm.rainbow, linewidths=5)
ax.add_collection(lines)
fig.colorbar(lines)
# Manually adding artists doesn't rescale the plot, so we need to autoscale
ax.autoscale()
plt.show()
from bokeh.io import output_file, show
from bokeh.plotting import figure
y = [0,1,2,3,4,5]
x = [0]*len(y)
z = [1,2,3,4,5]
p = figure(plot_width=500, plot_height=200, tools='')
[p.line([x[i],x[i+1]],[y[i],y[i+1]],line_color = get_color(1,5,z,Viridis256), line_width=4) for i,z in enumerate(z) ]
show(p)
from bokeh.palettes import Viridis256
curvlst = [hv.Curve([[x[i],y[i]],[x[i+1],y[i+1]]],line_color = get_color(1,5,z,Viridis256)) for i,z in enumerate(z) ]
hv.Overlay(curvlst)
WARNING:param.Curve26666: Setting non-parameter attribute line_color=#440154 using a mechanism intended only for parameters
You could use a so called dim transform by rewriting the function a little bit:
def get_color(val, min_val, max_val, palette):
return [palette[(int((val-min_val)*((len(palette)-1)/(max_val-min_val))+.5))]]
y = [0,1,2,3,4,5]
x = [0]*len(y)
z = [1,2,3,4,5]
hv.NdOverlay({z: hv.Curve(([x[i],x[i+1]], [y[i],y[i+1]])) for i, z in enumerate(z)}, kdims=['z']).opts(
'Curve', color=hv.dim('z', get_color, 1, 5, Viridis256))
That being said, I don't think you should have to manually colormap Curves so I've opened: https://github.com/pyviz/holoviews/issues/3764.
I think I found out..
from bokeh.palettes import Viridis256
def get_color(min_val, max_val, val, palette):
return palette[(int((val-min_val)*((len(palette)-1)/(max_val-min_val))+.5))]
curvlst = [hv.Curve([[x[i],y[i]],[x[i+1],y[i+1]]]).opts(color=get_color(1,5,z,Viridis256)) for i,z in enumerate(z) ]
hv.Overlay(curvlst)
Please let me know it this is good practise, or if you know a better way..
I have the following data frame my_df:
my_1 my_2 my_3
--------------------------------
0 5 7 4
1 3 5 13
2 1 2 8
3 12 9 9
4 6 1 2
I want to make a plot where x-axis is categorical values with my_1, my_2, and my_3. y-axis is integer. For each column in my_df, I want to plot all its 5 values at x = my_i. What kind of plot should I use in matplotlib? Thanks!
You could make a bar chart:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'my_1': [5, 3, 1, 12, 6], 'my_2': [7, 5, 2, 9, 1], 'my_3': [4, 13, 8, 9, 2]})
df.T.plot(kind='bar')
plt.show()
or a scatter plot:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'my_1': [5, 3, 1, 12, 6], 'my_2': [7, 5, 2, 9, 1], 'my_3': [4, 13, 8, 9, 2]})
fig, ax = plt.subplots()
cols = np.arange(len(df.columns))
x = np.repeat(cols, len(df))
y = df.values.ravel(order='F')
color = np.tile(np.arange(len(df)), len(df.columns))
scatter = ax.scatter(x, y, s=150, c=color)
ax.set_xticks(cols)
ax.set_xticklabels(df.columns)
cbar = plt.colorbar(scatter)
cbar.set_ticks(np.arange(len(df)))
plt.show()
Just for fun, here is how to make the same scatter plot using Pandas' df.plot:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'my_1': [5, 3, 1, 12, 6], 'my_2': [7, 5, 2, 9, 1], 'my_3': [4, 13, 8, 9, 2]})
columns = df.columns
index = df.index
df = df.stack()
df.index.names = ['color', 'column']
df = df.rename('y').reset_index()
df['x'] = pd.Categorical(df['column']).codes
ax = df.plot(kind='scatter', x='x', y='y', c='color', colorbar=True,
cmap='viridis', s=150)
ax.set_xticks(np.arange(len(columns)))
ax.set_xticklabels(columns)
cbar = ax.collections[-1].colorbar
cbar.set_ticks(index)
plt.show()
Unfortunately, it requires quite a bit of DataFrame manipulation just to call
df.plot and then there are some extra matplotlib calls needed to set the tick
marks on the scatter plot and colorbar. Since Pandas is not saving effort here,
I would go with the first (NumPy/matplotlib) approach shown above.