python reads excel data and draws histograms and line charts with dual y-axes, and the columns are filled with gradient colors

python drawing series article directory

往期python绘图合集:
python draws a simple line chart
python reads data in excel and draws multiple subgraphs and multiple groups of graphs on one canvas
python draws a histogram with error bars
python draws multiple subgraphs and displays them separately
python reads excel data and draws multiple y Axis image
python draws a histogram and beautifies it | Filling the columns with different colors
python randomly generates data and uses dual y-axes to draw two line charts with error bars
Python draws a histogram with error bars Gradient color filling with data annotation (advanced)
python drawing Scatter plot | Scatter size and color depth are determined by numerical values.
Matplotlib draws beautiful pie charts | python draws beautiful pie charts


1. Data preparation

The Excel file is read through Pandas's read_excel() function, converted into data frame format, and the font size and canvas size are set.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib

excel = pd.read_excel("C:/Users/ypzhao/Desktop/新能源汽车数据.xlsx")
data = pd.DataFrame(excel)
# 生成随机数据
x = data['年份']
y1 = data['销量']
y2 = data['增长率']
# 设置字体和字号
matplotlib.rcParams['font.family'] = 'Times New Roman'
matplotlib.rcParams['font.size'] = 24

font = {
    
    'family':'Times New Roman','size':28}
# 创建画布和子图
fig, ax1 = plt.subplots(figsize=(11,6),dpi=3000)

Insert image description here

2. Add y-axis

Use the ax1.bar() function to draw a bar chart, the ax2.plot() function to draw a line chart, set the axis labels and titles, and set the axis font and size.

# 设置字体和字号
matplotlib.rcParams['font.family'] = 'Times New Roman'
matplotlib.rcParams['font.size'] = 24

font = {
    
    'family':'Times New Roman','size':28}
# 创建画布和子图
fig, ax1 = plt.subplots(figsize=(11,6),dpi=3000)
ax2 = ax1.twinx()

3. Prepare color gradient

3.1 Prepare color gradient

n_groups = 6
cmap = plt.get_cmap('coolwarm')
colors_1 = [cmap(i) for i in np.linspace(0, 0.8, n_groups)]

# 绘制图
#绘制折线图
bar_plot=ax1.bar(x, y1, color=colors_1)
#绘制柱状图
ax2.plot(x, y2, color='green',marker='*',markersize=10)

3.2 Beautify the picture

# 设置坐标轴标签和标题
ax1.set_xlabel('年份',fontname='SimSun')
ax2.set_ylabel('增长率/%', color='#3F7F4C',fontname='SimSun')
ax1.set_ylabel('销量/万辆', color='#6D8F18',fontname='SimSun')

# 设置坐标轴字体和字号
for ax in [ax1, ax2]:
    ax.tick_params(axis='both', which='major', labelsize=20)
    for tick in ax.get_xticklabels() + ax.get_yticklabels():
        tick.set_fontname('Times New Roman')
        # 设置坐标轴标签和标题
ax1.set_xlabel('年份',fontname='SimSun')
ax2.set_ylabel('增长率/%', color='#3F7F4C',fontname='SimSun')
ax1.set_ylabel('销量/万辆', color='#6D8F18',fontname='SimSun')

# 设置坐标轴字体和字号
for ax in [ax1, ax2]:
    ax.tick_params(axis='both', which='major', labelsize=20)
    for tick in ax.get_xticklabels() + ax.get_yticklabels():
        tick.set_fontname('Times New Roman')
# 设置网格线不可见
ax1.grid(visible=False)
ax2.grid(visible=False)
ax2.set_ylim(-45,390)
ax1.set_ylim(0,730)

# 设置双坐标轴的颜色不一致
ax1.spines['left'].set_color('#6D8F18')
ax1.spines['right'].set_color('#3F7F4C')
ax1.tick_params(axis='y', colors='#6D8F18')
ax2.tick_params(axis='y', colors='#3F7F4C')
ax1.grid(visible=False)
ax2.grid(visible=False)
ax2.set_ylim(-45,390)
ax1.set_ylim(0,730)

# 设置双坐标轴的颜色不一致
ax1.spines['left'].set_color('#6D8F18')
ax1.spines['right'].set_color('#3F7F4C')
ax1.tick_params(axis='y', colors='#6D8F18')
ax2.tick_params(axis='y', colors='#3F7F4C')

3.3 Add data to the line chart

for i, j in zip(x, y2):
    ax.annotate('{:.2f}'.format(j), xy=(i, j), xytext=(-10, 10),
                textcoords='offset points', fontsize=16)

3.4 Adjust the histogram to add data

for rect in bar_plot:
    height = rect.get_height()
    ax1.text(rect.get_x() + rect.get_width()/2., height+1, '%.1f' % (height),
            ha='center', va='bottom', fontsize=16, color='blue',fontname='Times New Roman')  # 字体颜色蓝色
# 自动调整布局
plt.tight_layout()

Use rect.get_x() + rect.get_width()/2. to represent the position of the label text, directly above the center of the column; use rect.get_height()+0.5 to represent the height of the label text, slightly offset above the top of the column. ; The ha and va parameters are used to set the horizontal and vertical alignment of text labels respectively. Finally, f'{y[i]}' represents the label text content, that is, the column height.

4. Complete the code

# -*- coding: utf-8 -*-
"""
Created on Sat May 20 17:55:37 2023

@author: ypzhao
"""

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib

excel = pd.read_excel("C:/Users/ypzhao/Desktop/新能源汽车数据.xlsx")
data = pd.DataFrame(excel)

# 生成随机数据
x = data['年份']
y1 = data['销量']
y2 = data['增长率']

# 设置字体和字号
matplotlib.rcParams['font.family'] = 'Times New Roman'
matplotlib.rcParams['font.size'] = 24

font = {
    
    'family':'Times New Roman','size':28}
# 创建画布和子图
fig, ax1 = plt.subplots(figsize=(11,6),dpi=3000)
ax2 = ax1.twinx()



# 准备颜色渐变
n_groups = 6
cmap = plt.get_cmap('coolwarm')
colors_1 = [cmap(i) for i in np.linspace(0, 0.8, n_groups)]

# 绘制图
bar_plot=ax1.bar(x, y1, color=colors_1)
# 调整字体颜色、柱子宽度等其他参数

ax2.plot(x, y2, color='green',marker='*',markersize=10)


# 设置坐标轴标签和标题
ax1.set_xlabel('年份',fontname='SimSun')
ax2.set_ylabel('增长率/%', color='#3F7F4C',fontname='SimSun')
ax1.set_ylabel('销量/万辆', color='#6D8F18',fontname='SimSun')


# 设置坐标轴字体和字号
for ax in [ax1, ax2]:
    ax.tick_params(axis='both', which='major', labelsize=20)
    for tick in ax.get_xticklabels() + ax.get_yticklabels():
        tick.set_fontname('Times New Roman')

# 设置网格线不可见
ax1.grid(visible=False)
ax2.grid(visible=False)
ax2.set_ylim(-45,390)
ax1.set_ylim(0,730)

# 设置双坐标轴的颜色不一致
ax1.spines['left'].set_color('#6D8F18')
ax1.spines['right'].set_color('#3F7F4C')
ax1.tick_params(axis='y', colors='#6D8F18')
ax2.tick_params(axis='y', colors='#3F7F4C')

# 给折线图增添数据
for i, j in zip(x, y2):
    ax.annotate('{:.2f}'.format(j), xy=(i, j), xytext=(-10, 10),
                textcoords='offset points', fontsize=16)
    

# 调柱状图增加数据
for rect in bar_plot:
    height = rect.get_height()
    ax1.text(rect.get_x() + rect.get_width()/2., height+1, '%.1f' % (height),
            ha='center', va='bottom', fontsize=16, color='blue',fontname='Times New Roman')  # 字体颜色蓝色
# 自动调整布局
plt.tight_layout()

plt.savefig("sells.jpg",dpi=3000)

Six operation results

Insert image description here
This article involves data links and codes (click to get the data):

Guess you like

Origin blog.csdn.net/m0_58857684/article/details/130784673