【原创】用Matplotlib绘制的图表,真的是太惊艳了!!
當我們談論Python中的數據可視化,Matplotlib是一個不可或缺的庫。它強大的功能和靈活性使我們能夠以各種方式輕松地呈現數據。然而,有時候,我們可能會忽視Matplotlib在創建視覺上令人驚嘆的圖像方面的潛力。在本文中,我們將探討如何使用Matplotlib繪制出吸引人的、有趣的和美觀的圖像。
圓環圖中間帶有文字
我們可以在雙層圓環圖當中放置文字來代表關鍵的信息,例如我們整體的業績指標,通過該圖可以來顯示目前已經達到的進度,代碼如下
import?matplotlib.pyplot?as?plt import?pandas?as?pd import?numpy?as?npactual_value?=?45 target_value?=?120 remaining_value?=?target_value?-?actual_valuecolours?=?['#3da9d4',?'#063b63']fig?=?plt.figure(figsize=(10,10),?facecolor='#25253c') ax?=?fig.add_subplot(1,1,1)pie?=?ax.pie([55,?45],?colors=colours,?startangle=90,?labeldistance=1.15,?counterclock=False)pie[0][1].set_alpha(0.4)#?添加內圓環 centre_circle?=?plt.Circle((0,?0),?0.6,?fc='#25253c')#?Adding?the?circles?to?the?chart fig.gca().add_artist(centre_circle)#?添加文字 centre_text?=?f'${actual_value}K' centre_text_line_2?=?f'Total?Revenue'ax.text(0,0.1,?centre_text,?horizontalalignment='center',?verticalalignment='center',?fontsize=44,?fontweight='bold',color='white') ax.text(0,-0.1,?centre_text_line_2,?horizontalalignment='center',?verticalalignment='center',?fontsize=20,?fontweight='bold',color='grey')plt.show()output
從上面出來的結果中我們可以看到整個圓環代表的是整體的目標,也就是45K的整體業績指標,可以看到直觀的看到目前所處的進度,即55%,以及還未完成的部分,即45%。圓環中間我們也可以添加文字,來更加直觀對整個圖表做一個說明
甘特圖
甘特圖基本上是應用在項目管理當中,提供關于項目進度的相關內容,包括了
哪些項目是已經完成了的
哪些項目還未完成,當下的進度是如何
項目原定計劃的周期
等等
當然除了Matplotlib之外還有其他的模塊也能夠來繪制甘特圖,小編之前也寫了一篇相關的教程
【原創】用Python來繪制甘特圖并制作可視化大屏,太方便了!!
而用Matplotlib模塊繪制甘特圖的詳細的代碼如下
import?datetime import?matplotlib.pyplot?as?plt from?matplotlib.dates?import?datestr2num,?DateFormatter,?DayLocator from?matplotlib.ticker?import?AutoMinorLocator from?matplotlib.patches?import?Patch#?創建假數據 tasks?=?['Task?A',?'Task?B',?'Task?C',?'Task?D',?'Task?E',?'Task?F',?'Task?G',?'Task?H',?'Task?I',?'Task?J'] start_dates?=?['2023-02-25',?'2023-03-10',?'2023-03-13',?'2023-03-23',?'2023-04-01',?'2023-04-05',?'2023-04-12',?'2023-04-20',?'2023-04-24',?'2023-05-02'] end_dates?=?['2023-03-03',?'2023-03-17',?'2023-03-22',?'2023-03-30',?'2023-04-07',?'2023-04-18',?'2023-04-23',?'2023-04-25',?'2023-05-03',?'2023-05-07']#?創建項目的開始與結束時間 start_dates?=?[datestr2num(d)?for?d?in?start_dates] end_dates?=?[datestr2num(d)?for?d?in?end_dates]durations?=?[(end?-?start)?for?start,?end?in?zip(start_dates,?end_dates)]fig,?ax?=?plt.subplots(figsize=(15,?8),?facecolor='#25253c')ax.set_facecolor('#25253c')#?根據類目的不同來設定不同的顏色 colors?=?['#7a5195',?'#ef5675',?'#ffa600']? task_colors?=?[colors[0]]?*?3?+?[colors[1]]?*?4?+?[colors[2]]?*?3#?展示柱狀圖 ax.barh(y=tasks,?width=durations,?left=start_dates,? height=0.8,?color=task_colors)ax.invert_yaxis()#?X軸的坐標 ax.set_xlim(start_dates[0],?end_dates[-1])date_form?=?DateFormatter("%Y-%m-%d") ax.xaxis.set_major_formatter(date_form)ax.xaxis.set_major_locator(DayLocator(interval=10)) ax.xaxis.set_minor_locator(AutoMinorLocator(5)) ax.tick_params(axis='x',?which='minor',?length=2,?color='white',?labelsize=6)ax.get_yaxis().set_visible(False)ax.grid(True,?axis='x',?linestyle='-',?color='#FFFFFF',?alpha=0.2,?which='major') ax.grid(True,?axis='x',?linestyle='-',?color='#FFFFFF',?alpha=0.05,?which='minor') ax.set_axisbelow(True)#?給每一個任務添加注釋 for?i,?task?in?enumerate(tasks):ax.text(start_dates[i],?i,?f'??{task}',?ha='left',?va='center',?color='white',?fontsize=12,?fontweight='bold')#?添加時間軸 today?=?datetime.datetime.now().strftime("%Y-%m-%d") today_num?=?datestr2num(today) ax.axvline(today_num,?color='red',?alpha=0.8)#?X軸的注釋和標題設置 ax.tick_params(axis='both',?colors='white')ax.set_xlabel('Date',?color='white',?fontsize=12) ax.set_title('Project?Schedule',?color='white',?fontsize=14)#?橫軸和縱軸隱藏 ax.spines['left'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False)#?分類標注出來 legend_elements?=?[Patch(facecolor=colors[0],?label='Planning'),Patch(facecolor=colors[1],?label='Development'),Patch(facecolor=colors[2],?label='Testing'), ]#?添加注釋 ax.legend(handles=legend_elements,?loc='upper?right',?facecolor='white',?edgecolor='white',?fontsize=10,?title='Phases',?title_fontsize=12,?frameon=True)plt.show()output
從結果中我們可以看到每條任務的開始與結束的時間,以及所處的不同的狀態,有計劃中的任務、開發中的任務以及測試中的任務等等,基于當下的時間我們正處于哪項任務。
環狀條形圖
最后介紹一下環狀條形圖,整體效果會更加的驚艷,但是可讀性和前面二者相比可能會稍差一些,代碼如下
import?matplotlib.pyplot?as?plt import?pandas?as?pd import?numpy?as?np#?創建假數據 lith_dict?=?{'LITH':?['Shale',?'Sandstone',?'Sandstone/Shale',?'Chalk',?'Limestone',?'Marl',?'Tuff'],'PERCENTAGE':?[40,65,?40,?35,?40,?70,?50]} #?變成DataFrame格式 df?=?pd.DataFrame.from_dict(lith_dict)max_value_full_ring?=?max(df['PERCENTAGE'])ring_colours?=?['#003f5c',?'#374c80',?'#7a5195','#bc5090','#ef5675','#ff764a','#ffa600']ring_labels?=??[f'{x}?({v})'?for?x,?v?in?zip(list(df['LITH']),?list(df['PERCENTAGE']))] data_len?=?len(df) #?創建一個畫布出來 fig?=?plt.figure(figsize=(10,10),?facecolor='#393d5c')rect?=?[0.1,0.1,0.8,0.8]ax_cart?=?fig.add_axes(rect,?facecolor='#25253c') ax_cart.spines[['right',?'top',?'left',?'bottom']].set_visible(False) ax_cart.tick_params(axis='both',?left=False,?bottom=False,?labelbottom=False,?labelleft=False)ax_polar_bg?=?fig.add_axes(rect,?polar=True,?frameon=False) ax_polar_bg.set_theta_zero_location('N') ax_polar_bg.set_theta_direction(1)for?i?in?range(data_len):ax_polar_bg.barh(i,?max_value_full_ring*1.5*np.pi/max_value_full_ring,?color='grey',?alpha=0.1) #?隱藏掉所有的橫軸縱軸 ax_polar_bg.axis('off')ax_polar?=?fig.add_axes(rect,?polar=True,?frameon=False) ax_polar.set_theta_zero_location('N') ax_polar.set_theta_direction(1) ax_polar.set_rgrids([0,?1,?2,?3,?4,?5,?6],?labels=ring_labels,?angle=0,?fontsize=14,?fontweight='bold',color='white',?verticalalignment='center')#?遍歷所有的數據,然后繪制柱狀圖 for?i?in?range(data_len):ax_polar.barh(i,?list(df['PERCENTAGE'])[i]*1.5*np.pi/max_value_full_ring,?color=ring_colours[i])ax_polar.grid(False) ax_polar.tick_params(axis='both',?left=False,?bottom=False,?labelbottom=False,?labelleft=True)plt.show()output
總之,Matplotlib不僅僅是一個功能強大的數據可視化庫,它還可以作為一個有趣的工具,幫助我們在圖像設計和藝術創作中發揮想象力。當然,這里展示的只是冰山一角。Matplotlib的潛力遠不止于此,我們鼓勵你深入挖掘它的功能,嘗試更多有趣和創新的設計。
NO.1
往期推薦
Historical articles
簡直太逆天了,使用Python來檢測和識別車牌號碼(附代碼)
MySQL 常用腳本
介紹兩個好用到爆的Python模塊,建議收藏!!
嫌Python代碼慢?這個模塊讓Python提效100倍!!
分享、收藏、點贊、在看安排一下?
總結
以上是生活随笔為你收集整理的【原创】用Matplotlib绘制的图表,真的是太惊艳了!!的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python的高级应用
- 下一篇: 一个真实而又令人震撼的故事