깊은바다거북
개발 공부 기록
깊은바다거북
전체 방문자
오늘
어제
  • 분류 전체보기 (219)
    • JAVA (9)
    • JavaScript (15)
    • 스파르타코딩클럽 (11)
      • [내일배움단] 웹개발 종합반 개발일지 (5)
      • [내일배움캠프] 프로젝트와 트러블 슈팅 (6)
    • SQL | NoSQL (4)
    • CS 등등 (0)
    • TIL | WIL (173)
    • 기타 에러 해결 (3)
    • 내 살 길 궁리 (4)

인기 글

최근 글

최근 댓글

태그

  • 재귀 함수
  • 최소 힙(Min Heap)
  • tree
  • TypeScript
  • Leetcode
  • Binary Tree(이진 트리)
  • TIT (Today I Troubleshot)
  • 01. 미니 프로젝트
  • 점화식(Recurrence Relation)
  • 코딩테스트 연습문제
  • 트러블 슈팅 Troubleshooting
  • 자잘한 에러 해결
  • Inorder Traversal(중위 순회)
  • Linked List
  • DFS(깊이우선탐색)
  • POST / GET 요청
  • Trie
  • 팀 프로젝트
  • 자료 구조
  • 최대 힙(Max Heap)
  • 프로그래머스
  • 시간 복잡도
  • 자바스크립트 기초 문법
  • 혼자 공부하는 자바스크립트
  • BST(이진 탐색 트리)
  • Til
  • BFS(너비우선탐색)
  • Preorder Traversal(전위 순회)
  • Backtracking(백트래킹)
  • leetcode-cli
hELLO · Designed By 정상우.
깊은바다거북

개발 공부 기록

TIL | WIL

12/5 (화) D3.js로 그래프 자료구조 시각화하기 TIL

2023. 12. 5. 15:04

다음과 같이 생긴 노드-간선 그래프를 그리려고 한다.

  • 간선 데이터가 edges = [[1,2],[2,3],[3,4],[1,4],[1,5]] 와 같은 식으로 주어진다고 할 때, 그래프(Graph) 자료구조를 시각화하는 HTML, JS, CSS 코드는 다음과 같다(D3.js 라이브러리 활용):
    <!DOCTYPE html>
    <html>
    
    <head>
    	<title>Graph Visualization</title>
    	<script src="https://d3js.org/d3.v3.min.js"></script>
    	<style>
    		.link {
    			stroke: #999;
    			stroke-opacity: 0.6;
    		}
    
    		.node {
    			fill: #ccc;
    			stroke: #fff;
    			stroke-width: 1.5px;
    		}
    	</style>
    </head>
    
    <body>
    	<script>
    		// 간선 데이터
    		var edges = [
    			{ source: 1, target: 2 },
    			{ source: 2, target: 3 },
    			{ source: 3, target: 4 },
    			{ source: 1, target: 4 },
    			{ source: 1, target: 5 }
    		];
    
    		// 노드 데이터 생성
    		var nodes = {};
    		edges.forEach(function (edge) {
    			edge.source = nodes[edge.source] || (nodes[edge.source] = { id: edge.source });
    			edge.target = nodes[edge.target] || (nodes[edge.target] = { id: edge.target });
    		});
    
    		// SVG 요소의 크기
    		var width = 800, height = 600;
    
    		// D3.js force layout 설정
    		var force = d3.layout.force()
    			.nodes(d3.values(nodes))
    			.links(edges)
    			.size([width, height])
    			.linkDistance(150)
    			.charge(-800)
    			.on("tick", tick)
    			.start();
    
    		// SVG 요소 추가
    		var svg = d3.select("body").append("svg")
    			.attr("width", width)
    			.attr("height", height);
    
    		// 간선을 SVG 선으로 표현
    		var link = svg.selectAll(".link")
    			.data(force.links())
    			.enter().append("line")
    			.attr("class", "link");
    
    		// 노드를 SVG 원으로 표현
    		var node = svg.selectAll(".node")
    			.data(force.nodes())
    			.enter().append("g")
    			.attr("class", "node");
    
    		node.append("circle")
    			.attr("r", 20);  // 원의 반지름
    
    		// 노드에 번호 표시
    		node.append("text")
    			.attr("dx", -4)
    			.attr("dy", ".35em")
    			.style("fill", "black")  // 글자 색을 검정색으로 설정
    			.text(function (d) { return d.id; });
    
    		// 애니메이션을 위한 tick 함수
    		function tick() {
    			link.attr("x1", function (d) { return d.source.x; })
    				.attr("y1", function (d) { return d.source.y; })
    				.attr("x2", function (d) { return d.target.x; })
    				.attr("y2", function (d) { return d.target.y; });
    
    			node.attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; });
    		}
    	</script>
    	<h1>Hello</h1>
    </body>
    
    </html>
  • codePen에서 보기:
    https://codepen.io/soa6318/pen/qBgLaxP

출처: LeetCode #684. Redundant Connection 와 Edge Copilot


Uploaded by N2T

    'TIL | WIL' 카테고리의 다른 글
    • 11/14 (화) 대소문자를 모두 가지는 최장 부분 문자열 구하기 TIL
    • 11/3 (금) 합이 가장 큰 부분 배열 TIL
    • 11/2 (목) 쿼리를 포함하기 위한 최소 인터벌 TIL
    • 10/28 (토) (완료)인터벌이 안 겹치도록 삭제해야 하는 최소 인터벌 개수 TIL
    깊은바다거북
    깊은바다거북

    티스토리툴바