Conditions | 7 |
Total Lines | 131 |
Code Lines | 84 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | ''' |
||
49 | def missingval_plot(data, cmap='PuBuGn', figsize=(20, 12), sort=False, spine_color='#EEEEEE'): |
||
50 | ''' |
||
51 | Two-dimensional visualization of the missing values in a dataset. |
||
52 | |||
53 | Parameters |
||
54 | ---------- |
||
55 | data: 2D dataset that can be coerced into Pandas DataFrame. If a Pandas DataFrame is provided, the index/column \ |
||
56 | information is used to label the plots. |
||
57 | |||
58 | cmap: colormap, default 'PuBuGn' |
||
59 | Any valid colormap can be used. E.g. 'Greys', 'RdPu'. More information can be found in the matplotlib \ |
||
60 | documentation. |
||
61 | |||
62 | figsize: tuple, default (20,12) |
||
63 | Use to control the figure size. |
||
64 | |||
65 | sort: bool, default False |
||
66 | Sort columns based on missing values in descending order and drop columns without any missing values |
||
67 | |||
68 | spine_color: color-code, default '#EEEEEE' |
||
69 | Set to 'None' to hide the spines on all plots or use any valid matplotlib color argument. |
||
70 | |||
71 | Returns |
||
72 | ------- |
||
73 | figure |
||
74 | ''' |
||
75 | |||
76 | data = pd.DataFrame(data) |
||
77 | |||
78 | if sort: |
||
79 | mv_cols_sorted = data.isna().sum(axis=0).sort_values(ascending=False) |
||
80 | final_cols = mv_cols_sorted.drop(mv_cols_sorted[mv_cols_sorted.values == 0].keys().tolist()).keys().tolist() |
||
81 | data = data[final_cols] |
||
82 | print('Displaying only columns with missing values.') |
||
83 | |||
84 | # Identify missing values |
||
85 | mv_cols = _missing_vals(data)['mv_cols'] # data.isna().sum(axis=0) |
||
86 | mv_rows = _missing_vals(data)['mv_rows'] # data.isna().sum(axis=1) |
||
87 | mv_total = _missing_vals(data)['mv_total'] |
||
88 | mv_cols_ratio = _missing_vals(data)['mv_cols_ratio'] # mv_cols / data.shape[0] |
||
89 | total_datapoints = data.shape[0]*data.shape[1] |
||
90 | |||
91 | if mv_total == 0: |
||
92 | print('No missing values found in the dataset.') |
||
93 | else: |
||
94 | # Create figure and axes |
||
95 | fig = plt.figure(figsize=figsize) |
||
96 | grid = fig.add_gridspec(nrows=6, ncols=6, left=0.05, right=0.48, wspace=0.05) |
||
97 | ax1 = fig.add_subplot(grid[:1, :5]) |
||
98 | ax2 = fig.add_subplot(grid[1:, :5]) |
||
99 | ax3 = fig.add_subplot(grid[:1, 5:]) |
||
100 | ax4 = fig.add_subplot(grid[1:, 5:]) |
||
101 | |||
102 | # ax1 - Barplot |
||
103 | colors = plt.get_cmap(cmap)(mv_cols / np.max(mv_cols)) # color bars by height |
||
104 | ax1.bar(range(len(mv_cols)), np.round((mv_cols_ratio)*100, 2), color=colors) |
||
105 | ax1.get_xaxis().set_visible(False) |
||
106 | ax1.set(frame_on=False, xlim=(-.5, len(mv_cols)-0.5)) |
||
107 | ax1.set_ylim(0, np.max(mv_cols_ratio)*100) |
||
108 | ax1.grid(linestyle=':', linewidth=1) |
||
109 | ax1.yaxis.set_major_formatter(ticker.PercentFormatter(decimals=0)) |
||
110 | ax1.tick_params(axis='y', colors='#111111', length=1) |
||
111 | |||
112 | # annotate values on top of the bars |
||
113 | for rect, label in zip(ax1.patches, mv_cols): |
||
114 | height = rect.get_height() |
||
115 | ax1.text(.1 + rect.get_x() + rect.get_width() / 2, height+0.5, label, |
||
116 | ha='center', |
||
117 | va='bottom', |
||
118 | rotation='90', |
||
119 | alpha=0.5, |
||
120 | fontsize='small') |
||
121 | |||
122 | ax1.set_frame_on(True) |
||
123 | for _, spine in ax1.spines.items(): |
||
124 | spine.set_visible(True) |
||
125 | spine.set_color(spine_color) |
||
126 | ax1.spines['top'].set_color(None) |
||
127 | |||
128 | # ax2 - Heatmap |
||
129 | sns.heatmap(data.isna(), cbar=False, cmap='binary', ax=ax2) |
||
130 | ax2.set_yticks(np.round(ax2.get_yticks()[0::5], -1)) |
||
131 | ax2.set_yticklabels(ax2.get_yticks()) |
||
132 | ax2.set_xticklabels( |
||
133 | ax2.get_xticklabels(), |
||
134 | horizontalalignment='center', |
||
135 | fontweight='light', |
||
136 | fontsize='medium') |
||
137 | ax2.tick_params(length=1, colors='#111111') |
||
138 | for _, spine in ax2.spines.items(): |
||
139 | spine.set_visible(True) |
||
140 | spine.set_color(spine_color) |
||
141 | |||
142 | # ax3 - Summary |
||
143 | fontax3 = {'color': '#111111', |
||
144 | 'weight': 'normal', |
||
145 | 'size': 12, |
||
146 | } |
||
147 | ax3.get_xaxis().set_visible(False) |
||
148 | ax3.get_yaxis().set_visible(False) |
||
149 | ax3.set(frame_on=False) |
||
150 | |||
151 | ax3.text(0.1, 0.9, f"Total: {np.round(total_datapoints/1000,1)}K", |
||
152 | transform=ax3.transAxes, |
||
153 | fontdict=fontax3) |
||
154 | ax3.text(0.1, 0.7, f"Missing: {np.round(mv_total/1000,1)}K", |
||
155 | transform=ax3.transAxes, |
||
156 | fontdict=fontax3) |
||
157 | ax3.text(0.1, 0.5, f"Relative: {np.round(mv_total/total_datapoints*100,1)}%", |
||
158 | transform=ax3.transAxes, |
||
159 | fontdict=fontax3) |
||
160 | ax3.text(0.1, 0.3, f"Max-col: {np.round(mv_cols.max()/data.shape[0]*100)}%", |
||
161 | transform=ax3.transAxes, |
||
162 | fontdict=fontax3) |
||
163 | ax3.text(0.1, 0.1, f"Max-row: {np.round(mv_rows.max()/data.shape[1]*100)}%", |
||
164 | transform=ax3.transAxes, |
||
165 | fontdict=fontax3) |
||
166 | |||
167 | # ax4 - Scatter plot |
||
168 | ax4.get_yaxis().set_visible(False) |
||
169 | for _, spine in ax4.spines.items(): |
||
170 | spine.set_color(spine_color) |
||
171 | ax4.tick_params(axis='x', colors='#111111', length=1) |
||
172 | |||
173 | ax4.scatter(mv_rows, range(len(mv_rows)), s=mv_rows, c=mv_rows, cmap=cmap, marker=".", vmin=1) |
||
174 | ax4.set_ylim((0, len(mv_rows))[::-1]) # limit and invert y-axis |
||
175 | ax4.set_xlim(0, max(mv_rows)+0.5) |
||
176 | ax4.grid(linestyle=':', linewidth=1) |
||
177 | |||
178 | ax1.set_title('Missing value plot', pad=40, fontdict={'fontsize': 18}) |
||
179 | return grid |
||
180 | |||
298 |