我想要绘制的数据是这样的:x轴是0,7.5,15,22.5,30,y轴的数据是这样的:外科,内科,儿科,外科,外科,外科
时间: 2024-01-05 18:03:36 浏览: 75
JFreechart 双坐标Y轴 折点显示数据
好的,以下是一个绘制你所描述的数据的canvas代码示例:
```html
<template>
<canvas canvas-id="canvas" style="width: 100%; height: 400rpx;"></canvas>
</template>
<script>
export default {
onReady() {
const context = uni.createCanvasContext('canvas', this);
// 数据
const xAxisData = [0, 7.5, 15, 22.5, 30];
const yAxisData = ['外科', '内科', '儿科', '外科', '外科'];
// 绘制坐标轴
const startX = 50;
const startY = 350;
const chartWidth = 300;
const chartHeight = 250;
const axisWidth = 2;
const tickWidth = 5;
const tickGap = 10;
// x轴
context.beginPath();
context.moveTo(startX, startY);
context.lineTo(startX + chartWidth, startY);
context.lineWidth = axisWidth;
context.stroke();
xAxisData.forEach((item, index) => {
const x = startX + chartWidth / xAxisData.length * index;
const y = startY;
context.beginPath();
context.moveTo(x, y);
context.lineTo(x, y + tickWidth);
context.lineWidth = axisWidth;
context.stroke();
context.fillText(item, x - 10, y + tickWidth + tickGap);
});
// y轴
context.beginPath();
context.moveTo(startX, startY);
context.lineTo(startX, startY - chartHeight);
context.lineWidth = axisWidth;
context.stroke();
yAxisData.forEach((item, index) => {
const x = startX;
const y = startY - chartHeight / yAxisData.length * index - chartHeight / yAxisData.length / 2;
context.beginPath();
context.moveTo(x, y);
context.lineTo(x - tickWidth, y);
context.lineWidth = axisWidth;
context.stroke();
context.fillText(item, x - tickWidth - tickGap, y + 5);
});
// 绘制柱状图
const barWidth = chartWidth / xAxisData.length / 2;
const gap = barWidth / 2;
const data = ['外科', '内科', '儿科', '外科', '外科'];
data.forEach((item, index) => {
const x = startX + chartWidth / data.length * index + gap;
const y = startY - chartHeight / data.length * yAxisData.indexOf(item) - chartHeight / data.length / 2;
context.fillStyle = '#007aff';
context.fillRect(x, y, barWidth, chartHeight / data.length);
});
context.draw();
},
};
</script>
```
这个示例中,我们通过canvas绘制了一个简单的带坐标轴的柱状图,其中包括了x轴、y轴的绘制,柱状图的绘制,以及数据的处理。你可以根据自己的需要,修改其中的数据、样式等内容。
阅读全文