Add text for different part of line chart plot in plotly python - charts

I draw a figure using plotly (python) as shown in below.
Now my aim is to show all points in same color but add different text for each colored part from this figure. For example, for the blue part I want to add the text AAA and for the red part BBB. How to do that in plotly?

I have simulated data with features that will generate a graph similar to one you have shown
there are three ways to add labels
labels against traces in legend
as additional scatter plots with mode="text"
as annotations on the figure
All three of these are demonstrated below. It does assume you have a working knowledge of pandas
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
df = pd.DataFrame({"AAA":np.concatenate([np.random.uniform(1,5,20), np.full(20,np.nan)]),
"BBB":np.concatenate([np.full(20,np.nan), np.random.uniform(1,5,20), ])})
# create two traces, where traces are in legend to label AAA & BBB
fig = px.scatter(df, x=df.index, y=["AAA","BBB"]).update_traces(mode="lines+markers")
# additionally create text trace, that are last AAA & BBB
lastAAA = df.loc[~df["AAA"].isna()].iloc[-1]
lastBBB = df.loc[~df["BBB"].isna()].iloc[-1]
fig.add_trace(go.Scatter(x=[lastAAA.name], y=[lastAAA["AAA"]], text="AAA", mode="text", showlegend=False))
fig.add_trace(go.Scatter(x=[lastBBB.name], y=[lastBBB["BBB"]], text="BBB", mode="text", showlegend=False))
# additionally add annotations
fig.add_annotation(x=lastAAA.name, y=lastAAA["AAA"], text="AAA")
fig.add_annotation(x=lastBBB.name, y=lastBBB["BBB"], text="BBB")

Related

How to add title to graph_tool plot?

I'm using graph_tool to draw some graphs, and I don't see an obvious way to add a title to the output image.
If it is possible, how do I add a title?
The code I have right now draws a nice-looking graph, and I have added annotations to the vertices. But I haven't found a way to annotate the graph as a whole (like a title).
import graph_tool as gt
def draw_graph(g:gt.Graph):
ebet = gt.centrality.betweenness(g)[1]
pos = gt.draw.arf_layout(g)
gt.draw.graph_draw(
g,
pos=pos,
vertex_text=g.vertex_index,
edge_color=ebet,
vertex_size=gt.draw.prop_to_size(g.vertex_properties['size'], ma=50,log=False, power=1),
# vertex_fill_color=g.vertex_properties['size'],
output='tiny.pdf')
Graph-tool is not a full-fledged plot library, it focuses only on drawing graphs. To display titles, axes, legends, etc, it should be used together with matplotlib, as explained here: https://graph-tool.skewed.de/static/doc/demos/matplotlib/matplotlib.html

How can I get a graph of graphs to display in Sage?

I am working in SageMathCloud and have the following code:
import networkx
import matplotlib.pyplot as plt
test5 = networkx.Graph()
example = graphs.BuckyBall
test5.add_node(example)
networkx.draw(test5)
plt.show()
and from what I read, should display a graph with a single vertex that has a graph inside of it, like this picture from this article. However, all it shows is a single vertex with nothing inside of it as shown: Is there any way to display the graph to look like the 1st picture, where the graphs (as vertices) are shown?

ipython notebook read multiple images and display in CELL

How do I do the above ? This is my code but it doesn't work nothing is displayed
from PIL import Image
import glob
image_list = []
for filename in glob.glob('<my directory>.pgm'):
im=Image.open(filename)
image_list.append(im)
import matplotlib.pyplot as plt
for i in range(10):
plt.figure()
plt.imshow(image_list[i])
I would like it to be displayed in the cell
If you're interested in a much simpler and faster way of displaying images I recommend IPyPlot package:
import ipyplot
ipyplot.plot_images(images_list, max_images=20, img_width=150)
It's capable of displaying hundreds of images in a grid-like format within just 60-70ms
You would get a plot similar to this:
In your case, you should add %matplotlib inlinebefore your code and make sure that after plt.imshow(images_list) you add plt.show() as well so matplotlib renders your images.

Preserving Axis annotation while interactively zooming in on a matplotlib basemap plot?

I'm creating a figure displaying the worldmap with some data on it (which is irrelevant here). Now I want to be able to zoom in on it using the Pan/Zoom-button or the Zoom-to-rectangle-button and then save the figure to a picture file once I'm done zooming in. The problem is that the axis annotations (and the lng-/lat-lines) are "hard-embedded" in the picture, which make them vanish when you zoom in.
Does anybody know how to get axis annotations that adapt to the zooming?
Here is a minimal working example (without any data):
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np
fig = plt.figure(1, figsize=(12, 7))
m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,\
llcrnrlon=-180,urcrnrlon=180,resolution='l') #,lat_ts=20
m.drawcoastlines(); m.fillcontinents(); m.drawcountries()
# draw parallels and meridians.
m.drawparallels(np.arange(-90.,91.,30.),labels=[True, False, False, False], color='White')
m.drawmeridians(np.arange(-180.,181.,60.), labels=[False, False, False, True], color='White')
plt.show()
Just in case someone ever stumbles upon my question, here is what I came up with as a rather quick work-around. :-)
My intended application was to zoom in and then save the figure. Now I do not do that interactively but by entering the "zoomed bounding box" in the code and dynamically creating lng/lat-ticks with the following function (which needs an import numpy as np beforehand):
def calculateBasemapTicks(minMaxList, nrOfParalles = 3, nrOfMeridians = 3):
"""
Attempts to calculate meaningful ranges for .basemap.drawparallels
and .drawmeridians. Enter a <minMaxList> in the form
[lng_min, lng_max, lat_min, lat_max].
Note that you might get rather ugly floats. I suggest using formatting
as in ".drawparallels(..., fmt='%.4f')" or similar.
"""
pAdjust = (minMaxList[3]-minMaxList[2])*0.1
mAdjust = (minMaxList[1]-minMaxList[0])*0.1
parallels = np.linspace(minMaxList[2]+pAdjust,minMaxList[3]-pAdjust,
nrOfParalles)
meridians = np.linspace(minMaxList[0]+mAdjust,minMaxList[1]-mAdjust,
nrOfMeridians)
return parallels, meridians

Networkx: Importing graph with node values and edges information

I am generating random Geometric graph using networkx. I am exporting all the node and edges information into file.
I want to generate the same graph by importing all the node and edges information from file.
Code to export the node values and edge information.
G=nx.random_geometric_graph(10,0.5)
filename = "ipRandomGrid.txt"
fh=open(filename,'wb')
nx.write_adjlist(G, fh)
nx.draw(G)
plt.show()
I am trying to export it with below code and trying to change the color of some nodes. But it is generating different graph.
filename = "ipRandomGrid.txt"
fh=open(filename, 'rb')
G=nx.Graph()
G=nx.read_adjlist("ipRandomGrid.txt")
pos=nx.random_layout(G)
nx.draw_networkx_nodes(G,pos,nodelist=['1','2'],node_color='b')
nx.draw(G)
plt.show()
How to generate the same graph with few changes in color of some nodes?
If I understand the problem you're having correctly, the trouble is here:
pos=nx.random_layout(G)
nx.draw_networkx_nodes(G,pos,nodelist=['1','2'],node_color='b')
nx.draw(G)
You create a random layout of the graph in the first line, and use it to draw nodes '1' and '2' in the second line. You then draw the graph again in the third line without specifying the positions, which uses a spring model to position the nodes.
Your graph has no extra nodes, you've just drawn two of them in two different positions. If you want to consistently draw a graph the same way, you need to consistently use the pos you calculated. If you want it to be the same after storing and reloading, then save pos as well.
The easiest way to store node position data for your case might be using Python pickles. NetworkX has a write_gpickle() function that will do this for you. Note that the positions are already available as node attributes when you generate a random geometric graph so you probably want to use those when drawing. Here is an example of how to generate, save, load, and draw the same graph.
In [1]: import networkx as nx
In [2]: G=nx.random_geometric_graph(10,0.5)
In [3]: pos = nx.get_node_attributes(G,'pos')
In [4]: nx.draw(G,pos)
In [5]: nx.write_gpickle(G,'rgg.gpl')
In [6]: H=nx.read_gpickle('rgg.gpl')
In [7]: pos = nx.get_node_attributes(H,'pos')
In [8]: nx.draw(H,pos)