<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
andheight
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:
- Save as HTML: Save this code in an HTML file (e.g.,
chart.html
). - 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.
标签:attribute,一条,SVG,svg,axes,graph,折线图,line,more From: https://www.cnblogs.com/ai888/p/18604173