使用svg画一条折线图

<svg width="500" height="200">
  <polyline points="0,150 50,120 100,180 150,100 200,130 250,70 300,160 350,90 400,140 450,110 500,170"
            stroke="blue" stroke-width="2" fill="none" />

  <!-- Optional: Add axes and labels -->
  <line x1="0" y1="180" x2="500" y2="180" stroke="black" stroke-width="1" /> <!-- x-axis -->
  <line x1="0" y1="0" x2="0" y2="180" stroke="black" stroke-width="1" />   <!-- y-axis -->

</svg>

This code creates a simple line graph using SVG. Here's a breakdown:

  • <svg> element: This is the container for the entire graphic. width and height attributes define the SVG canvas size.
  • <polyline> element: This element draws the line graph.
    • points attribute: This is a list of x,y coordinates defining the points of the line. Each pair is separated by a space, and coordinates within a pair are separated by a comma. For example, "0,150" is the first point at x=0 and y=150. The y-axis in SVG starts from the top, so smaller y values are higher on the graph.
    • stroke attribute: Sets the color of the line (blue in this case).
    • stroke-width attribute: Sets the thickness of the line.
    • fill attribute: Set to "none" to prevent the area under the line from being filled.
  • Optional Axes and Labels: The commented-out lines show how to add simple x and y axes using <line> elements. You would need to add more elements (like <text>) to create labels for the axes and data points.

How to use this code:

  1. Save as HTML: Save this code in an HTML file (e.g., chart.html).
  2. Open in Browser: Open the HTML file in a web browser. The line graph will be displayed.

Key improvements for a better chart:

  • Data-driven approach: Instead of hardcoding the points attribute, generate it dynamically from your data using JavaScript. This makes the chart more flexible and reusable.
  • Scales and axes: Use proper scaling for the x and y axes to represent your data accurately. Libraries like D3.js are excellent for this.
  • Labels and titles: Add labels to the axes and a title to the chart to make it more informative.
  • Interactive elements: Consider adding tooltips or other interactive elements to enhance the user experience.

Using a library like D3.js is highly recommended for creating more complex and dynamic charts. While this example provides a basic understanding of how to draw a line graph with SVG, D3.js offers more powerful tools and features for data visualization.

posted @   王铁柱6  阅读(50)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· Apache Tomcat RCE漏洞复现(CVE-2025-24813)
点击右上角即可分享
微信分享提示