# Draw a "Lollipop chart" with Excel and python

Data Studio 2021-09-15 07:24:22
draw lollipop chart excel python

Hello everyone , I am cloud king ！

Today I'll bring you an interesting Visualization ——` Lollipop chart ` Detailed drawing tutorial . contrast Excel And Pyhton, Teach you to draw a lollipop chart on the tall with your hands .

## Excel Draw a lollipop chart

The first is data preparation , First copy the original data to a column , Get two columns of the same data .

Select data , Insert composite diagram , Set the combination chart of histogram and scatter chart respectively , After confirmation, you can get a preliminary lollipop chart .

You can set the corresponding style as required ：

Which set x The position of the shaft is relatively complex .

First select y Axis , Right click and then click Format axis , Next, set the abscissa position and abscissa label respectively . Set up x The axis value is 0.8, Or the axis you need . Set up x The axis label is at the bottom of the diagram .

The result is the following pattern .

Of course , You can set the style of bars and scatter points , Such as color, shape, etc . You can also select the style of a bar chart and scatter mark separately , To highlight one or more values .

## Python Draw a lollipop chart

### Bar+Scatter Combination method

The first method , and Excel The same way of thinking , Use a bar chart （plt.bar） And scatter plot （plt.scatter） Composite drawing . If you want a different style , You can style bar charts and scatter charts separately , To change the overall style .

```n = len(values)
colors1 = ["red"]+((n-1)*["olive"])
colors2 = ["red"]+((n-1)*["blue"])
plt.rcParams['figure.figsize'] = (23.5, 10)
plt.bar(values.index, values.values,
color=colors1, # Set the line color
width=0.05) # Set line width
plt.scatter(values.index, values.values,
color=colors2,# Set the marker point width
s=50) # Set marker point size
plt.show()
```

#### Set the style

This step mainly realizes X Move up axially .

• Will all y Value plus a fixed value v（ negative ）：`y = y+v`
• And set up y The lower limit of the axis is the fixed value v ：`plt.ylim(v, 0.6)`

Draw a horizontal line

• Draw a baseline by drawing a polyline , And fix it `y=0` `plt.plot(values.index, *n)`
• Or draw the baseline directly with the linear function , Same settings `y=0` `plt.axhline(y=0, xmin=0, xmax=1）`
• The above two methods can draw a straight line diagram , The disadvantage of the second method is that when setting the two ends of the line , It's not easy to control , because xmin and xmax The set value is in 0～1 The proportional value between . The second method can directly set the point values at both ends of the polyline .
```plt.style.use('ggplot')
# plt.style.use('dark_background') # Set the black background
plt.rcParams['figure.figsize'] = (23.5, 10)
plt.rcParams['axes.unicode_minus'] = False
v = -0.8
plt.bar(values.index, values.values+v,
color=colors1,width=0.05)
plt.scatter(values.index, values.values+v,
color=colors2,s=60)
# plt.plot(values.index,*n,color='darkblue')
plt.axhline(y=0,xmin=0.045, xmax=0.955,
color='darkblue' ,
linestyle='--')
plt.ylim(v,0.6)
plt.show()
```

### Stem Function method

stay python in , We make use of `matplotlib.pyplot.stem` You can draw a lollipop chart directly （ Stem and leaf ）. This function only needs one line of code to draw a lollipop chart . Let's take a look at the magical `plt.stem()` Main parameters of .

stem(x,y, linefmt=None, markerfmt=None, basefmt=None) x : array-like, optional data x Axis y : array-like data y Axis linefmt : str, optional You can use color and linetype to set the color and type of vertical lines , Such as `'r-'`, A solid red line . markerfmt : str, optional Set the type and color of vertices , The default value is :`'C0o'`,`C`( Capital C) By default , The last number should be 0-9, Color change , final `.` perhaps `o`（ Lowercase letters o） The vertices can be set as small real points or large real points respectively . basefmt : str, default: 'C3-' ('C2-' in classic mode) Defines the format string of the baseline attribute . Namely y=0 The right line

In terms of parameters , Use its parameters to set the color , You can only use... In the color circle set by this function 0-9 Number color . If you want to set other colors , You can use `plt.setp` To set the line style .

``` n = len(values2)
colors1 = ["red"]+((n-1)*["olive"])
(markers, stemlines, baseline) = plt.stem(values2, markerfmt="C0o")
plt.setp(stemlines,
linestyle="-",
color=colors1,
linewidth=0.5 ) # Specify the properties of each row
plt.setp(baseline,
linestyle="--",
color="darkblue",
linewidth=2 )
plt.show()
```

By setting parameters `bottom=0.8` To adjust the baseline position , And set the background style .

```plt.style.use('dark_background')
plt.grid(0)
(markers, stemlines, baseline) = plt.stem(values2,
bottom=0.8,
markerfmt="C3o")
plt.setp(stemlines, linestyle="-",
color="y", linewidth=2 )
plt.show()
```

Finally, when there is too much data , The effect of drawing a lollipop chart .

OK, Today's sharing is here ！

I didn't see enough. ？ Like watching Walk up ～ More exciting follow-up ～