使用 C++ 使用 openGL 以图形方式表示堆积条形图

represent a stacked bar chart graphically with openGL using C++

我想出了如何制作条形块,但我的问题是每个块底边的位置,我不知道如何让它们完美地堆叠在一起,所以大多数最终都是在另一个之上,使酒吧看起来不对劲。 这是我的功能:

void StackedBar(void)
{
// Clear the Screen
glClear(GL_COLOR_BUFFER_BIT);

float colors[6][3] = { { 1,0,0 },{ 1,1,0 },{ 0,1,0 },{ 0,1,1 },{ 1,0,1 },{0,0,1} };
float data[6] = { 20,66,42,28,71,23 };
float x = 0, y = 0;
float dy;

glBegin(GL_QUADS);
for (int i = 0; i < 6; i++) {
    glColor3f(colors[i][0], colors[i][1], colors[i][2]);
    dy = data[i];
    glVertex2f(x, y);
    glVertex2f(x + 5, y);
    glVertex2f(x + 5, y + dy);
    glVertex2f(x, y + dy);
    y  = dy;
    //x +=5; incremented x just to see how the pieces are positioned
}
glEnd();

// force execution of GL commands
glFlush();
}

输出:

result

result with x incremented with 5 just to see the pieces are positioned

如果您想将条形堆叠在一起,只需在每次迭代中将 y 递增 dy。

for (int i = 0; i < 6; i++) {
    glColor3f(colors[i][0], colors[i][1], colors[i][2]);
    dy = data[i];
    glVertex2f(x, y);
    glVertex2f(x + 5, y);
    glVertex2f(x + 5, y + dy);
    glVertex2f(x, y + dy);
    y += dy;
}