import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
# 解决matplotlib中文显示问题,仅适用windows系统
plt.rcParams['font.sans-serif'] = ['SimHei']
# 解决matplotlib中文显示问题,仅适用mac系统
def get_chinese_font():
return FontProperties(fname='/System/Library/Fonts/PingFang.ttc')
data_path = '/Users/miraco/PycharmProjects/DataMining/bikeshare'
data_filenames = ['2017-q1_trip_history_data.csv', '2017-q2_trip_history_data.csv',
'2017-q3_trip_history_data.csv','2017-q4_trip_history_data.csv']
#结果保存路径
output_path = './bikeshare/output'
if not os.path.exists(output_path): #如果不存在就新建一个
os.makedirs(output_path)
hist_range = (0,180)
n_bins = 12
def collect_and_process_data():
member_mean_duration_list, casual_mean_duration_list = [],[]
for filename in data_filenames:
file = os.path.join(data_path,filename)
data = np.loadtxt(file,delimiter=',',dtype= 'str',skiprows=1)
member_info_data = np.core.defchararray.replace(data[:,-1],'"','').reshape(-1,1) #这是会员信息列
duration_data = np.core.defchararray.replace(data[:, 0], '"', '').reshape(-1, 1) #这是骑行时长
member_data = duration_data[member_info_data[:,0]=='Member']
casual_data = duration_data[member_info_data[:,0] == 'Casual']
year_member_duration = member_data[:, 0].astype('float') / 1000 / 60
year_casual_duration = casual_data[:, 0].astype('float') / 1000 / 60
member_mean_duration_list.append(np.mean(year_member_duration))
casual_mean_duration_list.append(np.mean(year_casual_duration))
return member_mean_duration_list, casual_mean_duration_list
def save_and_show_results(member_mean_duration_list, casual_mean_duration_list):
bar_locs = np.arange(4) #四对柱子
bar_width = 0.35 #柱子宽度
xtick_labels = [f'第{i+1}季度' for i in range(4)] #x轴的标注
plt.figure()
plt.bar(bar_locs, #柱状图底线中点位置
member_mean_duration_list, #4对左侧柱子数据
width = bar_width, #宽度
color = 'g', #绿色
label = '会员' #标签
)#alpha表示透明度,0表示全透明,1表示完全不透明。
plt.bar(bar_locs + bar_width, #4对右侧柱子的中点位置,应该是左柱子右平移一个柱宽
casual_mean_duration_list, # 4对右侧柱子数据
width = bar_width, #宽度
color = 'r', #蓝色
label='非会员' #标签
)
plt.xticks(bar_locs + bar_width/2, #四个中刻线位置
xtick_labels, #刻线的标注,是一行四列矩阵
rotation = 45, #45倾角
fontproperties = get_chinese_font(), #字体
fontsize=14 #字大小
)
plt.ylabel('平均骑行时间(单位:分钟)', #y标签
fontproperties = get_chinese_font(), #字体
fontsize=14 #字大小
)
plt.title('柱状图', fontproperties = get_chinese_font())
plt.legend(loc = 'best',prop = get_chinese_font())
plt.tight_layout()
plt.savefig(os.path.join(output_path, 'riding_bars_chart.png'))
plt.show()
def main():
member_mean_duration_list, casual_mean_duration_list = collect_and_process_data()
save_and_show_results(member_mean_duration_list, casual_mean_duration_list)
if __name__ == '__main__':
main()
运行结果
会有警告信息,可以忽略:
>>>UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans
(prop.get_family(), self.defaultFamily[fontext]))
图
图
需要考虑的问题
绘制柱状图的时候,刻度和宽度
bar_locs = np.arange(4) #四对柱子
bar_width = 0.35 #柱子宽度
xtick_labels = [f'第{i+1}季度' for i in range(4)] #x轴的标注
plt.figure()
plt.bar(bar_locs, #柱状图底线中点位置
member_mean_duration_list, #4对左侧柱子数据
width = bar_width, #宽度
color = 'g', #绿色
label = '会员' #标签
)#alpha表示透明度,0表示全透明,1表示完全不透明。
plt.bar(bar_locs + bar_width, #4对右侧柱中点位置,应是左柱子右平移一个柱宽
casual_mean_duration_list, # 4对右侧柱子数据
width = bar_width, #宽度
color = 'r', #蓝色
label='非会员' #标签
)
plt.xticks(bar_locs + bar_width/2, #四个中刻线位置
xtick_labels, #刻线的标注,是一行四列矩阵
rotation = 45, #45倾角
fontproperties = get_chinese_font(), #字体
fontsize=14 #字大小
)
plt.ylabel('平均骑行时间(单位:分钟)', #y标签
fontproperties = get_chinese_font(), #字体
fontsize=14 #字大小
)
plt.title('柱状图', fontproperties = get_chinese_font())
plt.legend(loc = 'best',prop = get_chinese_font())
字体
from matplotlib.font_manager import FontProperties
# 解决matplotlib中文显示问题,仅适用windows系统
plt.rcParams['font.sans-serif'] = ['SimHei']
# 解决matplotlib中文显示问题,仅适用mac系统
def get_chinese_font():
return FontProperties(fname='/System/Library/Fonts/PingFang.ttc')
网友评论