Harshavardhan Ramanna - 10 months ago 47

Python Question

Code snippet looks like this

`#df is dataframe with 6 rows, with each row index being the label of the sector`

plt.pie(df.iloc[:,0], labels= df.index) #plot the first column of dataframe as a pie chart

It generates a pie chart like this:

Pie Chart with the 6 sectors.

As you can see, the sectors kitchen & entertainment are very small. I want to make each sector have a minimum value of 10 degree (1/36 %).

This would effectively mean fitting the data over 300 degrees (10 degree to each sector and we have 6 - Lighting, Entertainment, Kitchen, Cooling, Fridge, Others)

Answer

I want to make each sector have a minimum value of 10 degree

Solving this for the general case is difficult and requires further definition. This introduces a skew into the results, and to decide between different algorithms, you'd need to specify a metric defining how close is some skewed result to the original.

However, there is a very simple thing you can do which will guarantee your requirement. Say the length of your DataFrame is *n*, the sum of its elements is *s*, and you want the result to have no less than *α* (in your case, *α = 1./36*). If you would simply add some *x* to all elements, then the new sum would be

*s + nx*

Assuming that no element is negative, the smallest element would have weight at least *x / (s + nx)*.

Solving for

*x / (s + nx) = α*

Gives

*x = s α / (1 - αn)*.

So, if the Series you wish to pie-chart is `df.a`

, you could do

```
x = max(df.a.sum() * alpha / (1 - alpha * len(df)), 0)
```

and then plot instead `df.a + x`

.

**Example**

```
df = pd.DataFrame({'a': [1, 2, 3, 40, 40, 50, 50, 500]})
x = max(df.a.sum() * alpha / (1 - alpha * len(df)), 0)
```

You can check the smallest relative weight of `df.a + x`

```
(df.a + x).min() / (df.a + x).sum()
```

is indeed greater than *α*.

Source (Stackoverflow)