I want to draw a single networkX graph with items inside the tuple 'new'.
My graph nodes will have labels such as "AXIN", and color will be green or yellow.
I want the node to be green color, if 'UNREPORTED'.
If item[2] within tuple 'reported', I want this node to be yellow color.
> new = (('AXIN', 37, 'reported'), ('LGR', 30, 'reported'), ('NKD',
> 24, 'reported'), ('TNFRSF', 23, 'UNREPORTED'), ('CCND', 19,
> 'reported'), ('APCDD', 18, 'reported'), ('TR', 16, 'UNREPORTED'),
> ('TOX', 15, 'UNREPORTED'), ('LEF', 15, 'reported'), ('MME', 13,
> 'reported'))
>
> X, Y, _ = zip(*new) import seaborn as sns sns.set() import
> matplotlib.pyplot as plt %matplotlib inline plt.figure(figsize = (20,
> 10)) mytitle = "Most common genes coexpressed with {gene1}, {gene2},
> {gene3}, {gene4}".format(gene1="axin2", gene2="lef", gene3="nkd1",
> gene4="lgr5") plt.title(mytitle, fontsize=40) plt.ylabel('Number of
> same gene encounters across studies', fontsize=20) ax =
> plt.bar(range(len(X)), Y, 0.6, align='center', tick_label = X,
> color="red") ax = plt.xticks(rotation=90) new = tuple(new)
>
> import networkx as nx children = sorted(new, key=lambda x: x[1])
> parent = children.pop()[0]
>
> G = nx.Graph() for child, weight, _ in children: G.add_edge(parent,
> child, weight=weight) width = list(nx.get_edge_attributes(G,
> 'weight').values()) colors = [] for i in new:
> if i[2] == 'UNREPORTED':
> colors.append('green')
> elif i[2] == 'reported':
> colors.append('yellow') print(colors) plt.savefig("plt.gene-expression.pdf") plt.figure(figsize = (20, 10))
> mytitle = "Most common genes coexpressed with {gene1}, {gene2},
> {gene3}, {gene4}".format(gene1="axin2", gene2="lef", gene3="nkd1",
> gene4="lgr5") plt.title(mytitle, fontsize=40)
>
> nx.draw_networkx(G, font_size=10, node_size=2000, alpha=0.6,
> node_color=colors) plt.savefig("gene-expression-graph.pdf")
With this code, I get two different graphs, with yellow nodes, other with green nodes.
You could use a dictionary comprehension with the ternary operator to build a mapping of the nodes to colors. This can be used to color the nodes when drawing the graph.
import networkx as nx
new = (('AXIN', 37, 'reported'), ('LGR', 30, 'reported'), ('NKD', 24, 'reported'), ('TNFRSF', 23, 'UNREPORTED'), ('CCND', 19, 'reported'), ('APCDD', 18, 'reported'), ('TR', 16, 'UNREPORTED'), ('TOX', 15, 'UNREPORTED'), ('LEF', 15, 'reported'), ('MME', 13, 'reported'))
children = sorted(new, key=lambda x: x[1])
node_color = {node[0]: 'y' if node[2] == 'reported' else 'g' for node in children}
parent = children.pop()[0]
G = nx.Graph()
for child in children: G.add_edge(parent, child[0])
nx.draw_networkx(G, node_color=[node_color[i] for i in G.nodes()])
Related
I have a list of 51 elements.
keypoints = ['0.49395501613616943', '0.3686272203922272', '0.9999948740005493'...]. The original index of my list goes in order from 0,1,2...50. But i have to set new indices to the elements of the list and order them accordingly in a new list. How can i do that?
My new indices:
NEW_INDEX = [39, 40, 41, 21, 22, 23,
27, 28, 29, 33, 34, 35, 24, 25, 26,
30, 31, 32, 36, 37, 38, 42, 43, 44, 45, 46, 47,
48, 49, 50, 3, 4, 5, 9, 10, 11, 15, 16, 17,
6, 7, 8, 12, 13, 14, 18, 19, 20, 0, 1, 2]
Assuming this question is about python syntax.
In pure python, you can use a list comprehension and indices:
keypoints = ['0.49395501613616943', '0.3686272203922272', '0.9999948740005493', '0.9473770229920709', '0.7699773520016487', '0.540962426318277']
new_index = [2, 1, 5, 4, 0, 3]
ordered_keypoints = [keypoints[i] for i in new_index]
print(ordered_keypoints)
# ['0.9999948740005493', '0.3686272203922272', '0.540962426318277', '0.7699773520016487', '0.49395501613616943', '0.9473770229920709']
Using numpy, there is an even more convenient notation:
import numpy as np
keypoints = np.array(['0.49395501613616943', '0.3686272203922272', '0.9999948740005493', '0.9473770229920709', '0.7699773520016487', '0.540962426318277'])
new_index = np.array([2, 1, 5, 4, 0, 3])
ordered_keypoints = keypoints[new_index]
print(ordered_keypoints)
# ['0.9999948740005493' '0.3686272203922272' '0.540962426318277'
# '0.7699773520016487' '0.49395501613616943' '0.9473770229920709']
Here is the code:
from typing import Any
list = list(range(1, 41))
print(list)
listValues = []
for i in range(1, 5): # 1,2,3,4
value = int(input("Digite o valor:" + str(i) + ":")) # Digite o valor
listValues.append(value)
print(value)
for value in listValues:
print(value)
if value in list:
print("Valor " + str(value) + " encontrado.")
else:
print("Valor " + str(value) + " não encontrado.")
value = int(input("Digite o valor, para achar a posição:" +str(i) + ":"))
pos = listValues.append(value)
for i in range(len(list)):
if list[i] == value: pos = i
print(pos)
cont = list.count(value)
value = int(input("O valor" +str(i) + "aparece" + cont(value)))
As the last part of the code:
cont = list.count(value)
value = int(input("O valor" +str(i) + "aparece" + cont(value)))
doesn't recognize the action I want to play:
/usr/local/bin/python3.8 /Users/gss/Desktop/script/lista.py
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
Digite o valor:1:30
Digite o valor:2:20
Digite o valor:3:40
Digite o valor:4:50
50
30
Valor 30 encontrado.
20
Valor 20 encontrado.
40
Valor 40 encontrado.
50
Valor 50 não encontrado.
Digite o valor, para achar a posição:4:50
None
Traceback (most recent call last):
File "/Users/gss/Desktop/script/lista.py", line 23, in <module>
value = input("O valor" +str(i) + "aparece" + cont(value))
TypeError: 'int' object is not callable
Process finished with exit code 1
I don't know exactly what your are doing, I'm gonna get that out of the way first. Next I recommend not using python keywords for variable names, it seems to work as far as i saw but just a recommendation.
File "/Users/gss/Desktop/script/lista.py", line 23, in value = input("O valor" +str(i) + "aparece" + cont(value)) TypeError: 'int' object is not callable
This error is because you tried to use 'cont' variable as if it was a function.
You defined:
cont = list.count(value)
cont would be an int, that why you get the type error.
new = (('AXIN', 37, REPORTED),
('LGR', 34, REPORTED),
('NKD', 29, REPORTED),
('TNFRSF', 23, REPORTED),
('APCDD', 18, REPORTED),
('TOX', 15, UNREPORTED),
('LEF', 14, REPORTED),
('PLCB', 13, REPORTED),
('MME', 13, UNREPORTED),
('NOTUM', 13,UN REPORTED),
('GNG', 11, , REPORTED),
('LOXL', 10, UNREPORTED))
import matplotlib.pyplot as plt
import networkx as nx
children = sorted(new, key=lambda x: x[1])
parent = children.pop()[0]
G = nx.Graph()
for child, weight in children: G.add_edge(parent, child, weight=weight)
width = list(nx.get_edge_attributes(G, 'weight').values())
plt.savefig("plt.gene-expression.pdf")
plt.figure(figsize = (20, 10))
nx.draw_networkx(G, font_size=10, node_size=2000, alpha=0.6) #width=width is very fat lines
plt.savefig("gene-expression-graph.pdf")
In this nx graph, how can I make the UNREPORTED - green color, REPORTED-yellow color?
Parent node is the node with the largest number i.e., AXIN, 37
colors = []
for i in new:
if i[2] == 'UNREPORTED':
colors.append('green')
elif i[2] == 'REPORTED':
colors.append('yellow')
nx.draw_networkx(G, font_size=10, node_size=2000, alpha=0.6, node_color=colors)
The mismatch in ordering comes from the dictionaries that underlie networkx's graph representation. If you ensure that the list of colors is ordered the same way you will have the right color for the right node.
I've written two different approaches here that achieve what I think you want.
Note: I declared values for reported and unreported, rather than turning the third piece of every tuple into a string. But this part isn't essential
# Delcare the graph:
REPORTED = 1
UNREPORTED = 2
new = (('AXIN', 37, REPORTED),
('LGR', 34, REPORTED),
<...>
('LOXL', 10, UNREPORTED))
# 2 axes to show different approaches
plt.figure(1); plt.clf()
fig, ax = plt.subplots(1, 2, num=1, sharex=True, sharey=True)
### option 1: draw components step-by-step
# positions for drawing of all components in right place
pos = nx.spring_layout(G)
# identify which nodes are reported/unreported
nl_r = [name for (name, w, state) in new if state == REPORTED]
nl_u = [name for (name, w, state) in new if state == UNREPORTED]
# draw each subset of nodes in relevant color
nx.draw_networkx_nodes(G, pos=pos, nodelist=nl_r, node_color='g', nodesize=2000, ax=ax[0])
nx.draw_networkx_nodes(G, pos=pos, nodelist=nl_u, node_color='y', nodesize=2000, ax=ax[0])
# also need to draw the egdes
nx.draw_networkx_edges(G, pos=pos, ax=ax[0])
nx.draw_networkx_labels(G, pos=pos, ax=ax[0], font_size=10)
### option 2: more complex color list construction (but simpler plot command)
nl, cl = zip(*[(name, 'g') if state == REPORTED else (name, 'y') for (name, w, state) in new])
nx.draw_networkx(G, pos=pos, nodelist=nl, node_color=cl, nodesize=2000, ax=ax[1], font_size=10)
plt.show()
I'm trying to plot a graph that shows the average call duration every day each minute for 7 days in the same plot, now I'm defining the function that will give me the data asked according to conditions which will be plotted but I'm always getting a list of empty lists.can any one help me tof ind the bug? (acc is just an example of data from the global database)
This is the function:
import time
import calendar
from datetime import datetime
from itertools import repeat
acc=[{u'switch_id': 3, u'hangup_cause_id': 7, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 1), u'duration': 32}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 8), u'duration': 20}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 10), u'duration': 17}]
t = datetime.now()
y = t.year
m = t.month
d = t.day
donnees=[]
for k in range(7):
try:
m = t.month
data=[]
liste=[]
liste_time=[]
for i in acc:
if (i["start_uepoch"].year == y and i["start_uepoch"].month == m and i["start_uepoch"].day == d-k):
liste.append([i["start_uepoch"],i["duration"]])
for q in range(24):
for mnt in range(60):
liste2=[]
ACD=0
somme_duration=0
n=0
for p in liste:
if (p[0].hour==q and p[0].minute == mnt):
liste2.append(p[1])
temps=p[0]
if len(liste2)!=0:
for j in liste2:
somme_duration+=j
n+=1
ACD=round((float(somme_duration)/n)*100)/100
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(ACD)
else:
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(0)
except:
pass
donnees.append(data)
print donnees
This is due to your try / except condition, if you remove it by settings temps = None after your loop it solves you issue :
import time
import calendar
from datetime import datetime
from itertools import repeat
acc=[{u'switch_id': 3, u'hangup_cause_id': 7, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 1), u'duration': 32}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 8), u'duration': 20}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 10), u'duration': 17}]
t = datetime.now()
y = t.year
m = t.month
d = t.day
donnees=[]
for k in range(7):
m = t.month
data=[]
liste=[]
liste_time=[]
for i in acc:
if (i["start_uepoch"].year == y and i["start_uepoch"].month == m and i["start_uepoch"].day == d-k):
liste.append([i["start_uepoch"],i["duration"]])
for q in range(24):
for mnt in range(60):
temps = None
liste2=[]
ACD=0
somme_duration=0
n=0
for p in liste:
if (p[0].hour==q and p[0].minute == mnt):
liste2.append(p[1])
temps=p[0]
if temps:
if len(liste2)!=0:
for j in liste2:
somme_duration+=j
n+=1
ACD=round((float(somme_duration)/n)*100)/100
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(ACD)
else:
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(0)
donnees.append(data)
print donnees
liste = [1,2,8,12,19,78,34,197,1,-7,-45,-97,-32,23]
liste2 = []
def repetisjon(liste,liste2):
for count in liste:
if count > 0:
liste2.append(1)
elif count < 0:
liste2.append(0)
return liste2
return (liste2)
print (repetisjon(liste,liste2))
The point is to change all the values of the list. If it's greater than or equal to 0, it is to be replaced by the value 1. And if it's lower than 0, it is to be replaced by 0. But I wasn't able to change the current list. The only solution I found was to make a new list. But is there anyway to CHANGE the current list without making a new one? I tried this as well, but didnt work at all:
liste = [4,8,43,4,78,24,8,45,-78,-6,-7,-3,8,-12,4,36]
def repe (liste):
for count in liste:
if count > 0:
count == 1
else:
count == 0
print (liste)
repe(liste)
Here, I replace the content of liste with the transformed data. since sameliste points to the same list, its value changes too.
>>> sameliste = liste = [1,2,8,12,19,78,34,197,1,-7,-45,-97,-32,23]
>>> sameliste
[1, 2, 8, 12, 19, 78, 34, 197, 1, -7, -45, -97, -32, 23]
>>> liste
[1, 2, 8, 12, 19, 78, 34, 197, 1, -7, -45, -97, -32, 23]
>>> liste[:] = [int(x >= 0) for x in liste]
>>> liste
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1]
>>> sameliste
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1]
>>>