简体   繁体   English

饼图着色

[英]Pie chart coloring

I want to create a pie chart without using the command 'pie' in matlab. 我想创建一个饼图而不在matlab中使用命令“ pie”。 I have somehow managed but I have failed to color the segments. 我以某种方式进行了管理,但是我没有给段着色。 can someone help me how i can do so: below is my code: 有人可以帮助我该怎么做:以下是我的代码:

function pie_chart

r = 1;
v = [10 15 20 25 30];

C = ['r' 'g' 'b' 'm' 'c'];

t= 0:0.01:2*pi;

x = r * cos(t);
y = r * sin(t);

plot(x,y, 'k');hold on

for k=1:length(v)

  t=[v/sum(v)*2*pi];

  for t=1:length(t)

    x=[0 r *cos(t)];
    y=[0 r *sin(t)];

    plot(x,y); hold on

    fill(x,y,'C');

  end

  axis square

  axis off

end

There were a few errors in your code: 您的代码中存在一些错误:

When you declare C = ['r' 'g' 'b' 'm' 'c']; 当您声明C = ['r' 'g' 'b' 'm' 'c']; you concatenate the strings between the [] , so you ended up with C='rgbmc' . 您将[]之间的字符串连接起来,所以最后得到C='rgbmc' It is better to declare it as a cell array, by using the curly braces {} . 最好使用花括号{}将其声明为cell数组。 So your declaration becomes: C = {'r' 'g' 'b' 'm' 'c'}; 因此,您的声明将变为: C = {'r' 'g' 'b' 'm' 'c'};

The fill function needs an enclosed area to fill. fill功能需要一个封闭区域来填充。 You were sending only 2 points coordinates to the function (so basically a line), so it was only coloring the line. 您只向该函数发送了2个点坐标(因此基本上就是一条线),因此它只是给线着色。

Actually, it wasn't even coloring because you were specifying 'C' as the color. 实际上,它甚至没有着色,因为您将'C'指定为颜色。 You have to send one of the string contained in your cell array of color: C{k} 您必须发送包含在单元格颜色数组中的字符串之一: C{k}

Lastly, you do not need a double loop, a single loop over your different quadrant is enough (you were defining t in the outer loop, then immediately overwriting it when declaring the second loop). 最后,您不需要双循环,只需在不同象限上进行一个循环即可(您在外部循环中定义了t ,然后在声明第二个循环时立即覆盖了它)。

The following code produces the colored pie chart. 以下代码生成彩色饼图。 If you do not understand some aspects, I suggest you run it line by line and look at the variable content in the workspace. 如果您不了解某些方面,建议您逐行运行它,并查看工作空间中的变量内容。

function pie_chart

% Define quadrants and color
r = 1;
v = [10 15 20 25 30];
C = {'r' 'g' 'b' 'm' 'c'};

theta = linspace(0,2*pi,359) ;
idx_spokes = round( [1 cumsum(v)/100*length(theta) ] ) ; %// find the indices of the spokes

for k=1:length(idx_spokes)-1

   t = theta( idx_spokes(k):idx_spokes(k+1) ) ;

   x=[0 r*cos(t) 0];
   y=[0 r*sin(t) 0];
   plot(x,y); hold on
   fill(x,y, C{k} );
end

axis square
axis off

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM