При создании сетевой диаграммы некоторые узлы отображаются неправильными цветами категорий.
Я написал следующий код, который создает сетевую диаграмму. Он считывает данные из двух файлов CSV — одного для матрицы смежности, другого для категорий. Он предполагает раскрашивать узлы в зависимости от категории, к которой они принадлежат, но в конечном итоге некоторые узлы окрашиваются неправильно. Сначала я подумал, что проблема связана с использованием макета оболочки, но это случается и тогда, когда я делаю это с разными макетами. Если предположить, что с CSV-файлами все в порядке (категории определены правильно, нет несоответствий между матрицей и категориями и т. д.), в чем может быть проблема?
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
def create_network_diagram_from_csv(adjacency_csv_path, categories_csv_path):
# Read data from CSV into pandas DataFrames
df_adjacency = pd.read_csv(adjacency_csv_path, index_col=0)
df_categories = pd.read_csv(categories_csv_path, index_col=0)
# Convert DataFrames to NumPy arrays for easier handling
adjacency_matrix = df_adjacency.to_numpy()
# Get the node names from the DataFrame's index
nodes = df_adjacency.index.to_list()
# Create a directed graph using networkx
G = nx.DiGraph()
# Iterate through the adjacency matrix and add edges to the graph
for i, source_node in enumerate(nodes):
for j, target_node in enumerate(nodes):
edge_weight = adjacency_matrix[i, j]
if not pd.isna(edge_weight) and edge_weight > 0:
G.add_edge(source_node, target_node)
# Create the network diagram using shell layout
pos = nx.shell_layout(G)
# Get categories for each node from the categories DataFrame
categories = df_categories.to_dict()['Category']
# Define a mapping of categories to colors
category_colors = {
'category_a': 'green',
'category_b': 'blue',
'category_c': 'yellow',
'category_d': 'brown',
'category_e': 'red',
}
# Get the colors for each node based on its category
node_colors = [category_colors.get(categories[node], 'gray') for node in nodes]
# Customize node size
node_size = 300
# Draw the network diagram with nodes colored based on categories
nx.draw(G, pos, with_labels=True, node_size=node_size, node_color=node_colors, font_size=10, arrows=True)
#Create a custom legend for categories and colors
legend_elements = [plt.Line2D([0], [0], marker='o', color='w', label=category, markerfacecolor=color, markersize=10) for category, color in category_colors.items()]
# Add the legend to the plot
plt.legend(handles=legend_elements, title='Categories', loc='upper right', frameon=True)
edge_color = 'grey' # Specify the color of the arrows
# Draw the edges with the specified edge color
nx.draw_networkx_edges(G, pos, arrows=True, edge_color=edge_color)
plt.show()
adjacency_csv_path = r'C:\location of file'
categories_csv_path = r'C:\location of file'
create_network_diagram_from_csv(adjacency_csv_path, categories_csv_path)
Данные категории:
Node, Category
node_1, category_a
node_2, category_b
node_3, category_d
node_4, category_a
node_5, category_a
Данные о смежности:
,node_1,node_2,node_3,node_4,node_5
node_1, 1, 0, 0, 0, 1
node_2, 0, 0, 1, 0, 0
node_3, 0, 1, 0, 1, 1
node_4, 0, 1, 0, 1, 0
node_5, 1, 1, 1, 1, 1
Подробнее здесь: https://stackoverflow.com/questions/768 ... rk-diagram
Неправильный цвет узлов при создании сетевой диаграммы. ⇐ Python
Программы на Python
-
Anonymous
1769078147
Anonymous
При создании сетевой диаграммы некоторые узлы отображаются неправильными цветами категорий.
Я написал следующий код, который создает сетевую диаграмму. Он считывает данные из двух файлов CSV — одного для матрицы смежности, другого для категорий. Он предполагает раскрашивать узлы в зависимости от категории, к которой они принадлежат, но в конечном итоге некоторые узлы окрашиваются неправильно. Сначала я подумал, что проблема связана с использованием макета оболочки, но это случается и тогда, когда я делаю это с разными макетами. Если предположить, что с CSV-файлами все в порядке (категории определены правильно, нет несоответствий между матрицей и категориями и т. д.), в чем может быть проблема?
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
def create_network_diagram_from_csv(adjacency_csv_path, categories_csv_path):
# Read data from CSV into pandas DataFrames
df_adjacency = pd.read_csv(adjacency_csv_path, index_col=0)
df_categories = pd.read_csv(categories_csv_path, index_col=0)
# Convert DataFrames to NumPy arrays for easier handling
adjacency_matrix = df_adjacency.to_numpy()
# Get the node names from the DataFrame's index
nodes = df_adjacency.index.to_list()
# Create a directed graph using networkx
G = nx.DiGraph()
# Iterate through the adjacency matrix and add edges to the graph
for i, source_node in enumerate(nodes):
for j, target_node in enumerate(nodes):
edge_weight = adjacency_matrix[i, j]
if not pd.isna(edge_weight) and edge_weight > 0:
G.add_edge(source_node, target_node)
# Create the network diagram using shell layout
pos = nx.shell_layout(G)
# Get categories for each node from the categories DataFrame
categories = df_categories.to_dict()['Category']
# Define a mapping of categories to colors
category_colors = {
'category_a': 'green',
'category_b': 'blue',
'category_c': 'yellow',
'category_d': 'brown',
'category_e': 'red',
}
# Get the colors for each node based on its category
node_colors = [category_colors.get(categories[node], 'gray') for node in nodes]
# Customize node size
node_size = 300
# Draw the network diagram with nodes colored based on categories
nx.draw(G, pos, with_labels=True, node_size=node_size, node_color=node_colors, font_size=10, arrows=True)
#Create a custom legend for categories and colors
legend_elements = [plt.Line2D([0], [0], marker='o', color='w', label=category, markerfacecolor=color, markersize=10) for category, color in category_colors.items()]
# Add the legend to the plot
plt.legend(handles=legend_elements, title='Categories', loc='upper right', frameon=True)
edge_color = 'grey' # Specify the color of the arrows
# Draw the edges with the specified edge color
nx.draw_networkx_edges(G, pos, arrows=True, edge_color=edge_color)
plt.show()
adjacency_csv_path = r'C:\location of file'
categories_csv_path = r'C:\location of file'
create_network_diagram_from_csv(adjacency_csv_path, categories_csv_path)
Данные категории:
Node, Category
node_1, category_a
node_2, category_b
node_3, category_d
node_4, category_a
node_5, category_a
Данные о смежности:
,node_1,node_2,node_3,node_4,node_5
node_1, 1, 0, 0, 0, 1
node_2, 0, 0, 1, 0, 0
node_3, 0, 1, 0, 1, 1
node_4, 0, 1, 0, 1, 0
node_5, 1, 1, 1, 1, 1
Подробнее здесь: [url]https://stackoverflow.com/questions/76802885/wrong-colour-for-nodes-when-creating-network-diagram[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия