Technical Reference¶
Data Import¶
Defines the central data type along with importing logic.
LimeSurveyData(structure_file, responses_file)
¶
Base LimeSurvey class.
Parameters:
-
structure_file(Path) –path to the structure XML file
-
responses_file(Path) –path to the responses CVS file
Source code in src/survey_framework/data_import/data_import.py
__str__()
¶
Print all questions, responses and sections for debugging.
Source code in src/survey_framework/data_import/data_import.py
export_Qs_to_CSV(output_path)
¶
Export the question sheet from the survey to CSV.
Parameters:
-
output_path(Path) –output path to where CSV is saved
Source code in src/survey_framework/data_import/data_import.py
get_choices(question)
¶
Get choices of a question.
- For multiple-choice group, format is
<subquestion code: subquestion title>, for example, {"C3_SQ001": "I do not like scientific work.", "C3_SQ002": ...} - For all other fixed questions (i.e. array, single choice, subquestion), returns choices of that question or column
- For free and contingent, returns None
Parameters:
-
question(str) –Name of question or subquestion to retrieve
Returns:
Source code in src/survey_framework/data_import/data_import.py
get_question(question, drop_other=False)
¶
Get question structure (i.e. subset from self.questions).
Parameters:
-
question(str) –Name of question or subquestion
-
drop_other(bool, default:False) –Whether to exclude contingent question (i.e. "other")
Raises:
-
ValueError–There is no such question or subquestion
Returns:
-
DataFrame–pd.DataFrame: Subset from
self.questionswith corresponding rows
Source code in src/survey_framework/data_import/data_import.py
get_question_type(question)
¶
Get question type and validate it.
Parameters:
-
question(str) –question or column code
Raises:
-
AssertionError–Unconsistent question types within question
-
ValueError–Unexpected question type
Returns:
-
QuestionType(QuestionType) –Question type like "single-choice", "array", etc.
Source code in src/survey_framework/data_import/data_import.py
get_questions_by_type(type)
¶
Get a list of all questions with the given QuestionType.
Parameters:
-
type(QuestionType) –Desired QuestionType, e.g. SINGLE_CHOICE.
Returns:
Source code in src/survey_framework/data_import/data_import.py
get_responses(question, drop_other=False)
¶
Get responses for given question with or without contingent questions.
Parameters:
-
question(str) –Question to get the responses for.
-
drop_other(bool, default:False) –Whether to exclude contingent question (i.e. "other")
Raises:
-
ValueError–Inconsistent question types within question groups.
-
ValueError–Unknown question types.
Returns:
-
DataFrame–The response data for the selected question.
Source code in src/survey_framework/data_import/data_import.py
Data Aggregation¶
Convert raw dataframes into cleaned, sorted, counted dataframes ready for plotting.
We have specific functions for single-choice and multiple-choice questions, as well as "grouped" variants for both (which can be used for comparison barplots).
prepare_df_comparison(responses_df_all, responses_df_comparison, q, q_comparison, ordering)
¶
Compare groups of participants (determined by comparison_series).
This function is for single-choice questions.
The output dataframe contains the following columns
- q: The answer options
- q_comparison: The groups
- total: total number of participants in this group
- count: number of participants (in this group) that gave this answer
- proportion: share of participants (relative to "total") that gave this answ.
Parameters:
-
responses_df_all(DataFrame) –DataFrame with answers for the base question
-
responses_df_comparison(Series[str]) –Answers for the intersecting question
-
q(str) –name of the output column for answer options
-
q_comparison(str) –name of the output column for groups
-
ordering(dict[str, list[str]]) –Answer re-ordering dict, e.g. ORDER from
order/order2024.py
Returns:
-
tuple[DataFrame, dict[Hashable, int]]–Tuple of [DataFrame, group size dict]. The latter is used as N in plots.
Source code in src/survey_framework/data_analysis/count_responses.py
prepare_df_comparison_multiple(responses_df, comparison_series, q, q_comparison, ordering)
¶
Compare groups of participants (determined by comparison_series).
This function is for multiple-choice questions.
The output dataframe contains the following columns
- q: The answer options
- q_comparison: The groups
- total: total number of participants in this group
- count: number of participants (in this group) that gave this answer
- proportion: share of participants (relative to "total") that gave this answ.
Parameters:
-
responses_df(DataFrame) –The main DataFrame of answers
-
comparison_series(Series[str]) –Participant group (shares index with the main DF)
-
q(str) –name of the output column for answer options
-
q_comparison(str) –name of the output column for groups
-
ordering(dict[str, list[str]]) –Answer re-ordering dict, e.g. ORDER from
order/order2024.py
Returns:
-
tuple[DataFrame, dict[Hashable, int]]–Tuple of [DataFrame, group size dict]. The latter is used as N in plots.
Source code in src/survey_framework/data_analysis/count_responses.py
prepare_df_multiple(data, q, ordering)
¶
Count participants in the data. This function is for multiple-choice questions.
The output dataframe contains the following columns
- q: The answer options
- count: number of participants (in this group) that gave this answer
- proportion: share of participants (relative to "total") that gave this answ.
Parameters:
-
data(DataFrame) –The main DataFrame of answers
-
q(str) –name of the output column for answer options
-
ordering(dict[str, list[str]]) –Answer re-ordering dict, e.g. ORDER from
order/order2024.py
Returns:
Source code in src/survey_framework/data_analysis/count_responses.py
prepare_df_single(data, q, ordering)
¶
Count participants in the data. This function is for single-choice questions.
The output dataframe contains the following columns
- q: The answer options
- count: number of participants (in this group) that gave this answer
- proportion: share of participants (relative to "total") that gave this answ.
Parameters:
-
data(DataFrame) –The main DataFrame of answers
-
q(str) –name of the output column for answer options
-
ordering(dict[str, list[str]]) –Answer re-ordering dict, e.g. ORDER from
order/order2024.py
Returns:
Source code in src/survey_framework/data_analysis/count_responses.py
Basic filtering and aggreation of survey data.
filter_by_center(survey, responses, center_code)
¶
Filter responses by center.
Parameters:
-
survey(LimeSurveyData) –The survey object
-
responses(DataFrame) –DataFrame with responses
-
center_code(str) –ID of the center to filter by (like 'A01')
Returns:
-
tuple[DataFrame, DataFrame]–Tuple of filtered DataFrame and remainder DataFrame
Source code in src/survey_framework/data_analysis/analysis.py
get_as_numeric(survey, q_code, blocklist)
¶
Get numeric answers for the requested question code.
Raises:
-
ValueError–if non-numeric answer codes are not in the given blocklist.
Parameters:
-
survey(LimeSurveyData) –The survey object
-
q_code(str) –The question ID to be queried
-
blocklist(list[str]) –Answer codes to be excluded from the result
Returns:
-
Series[float]–Numeric Series
Source code in src/survey_framework/data_analysis/analysis.py
get_center_series(survey, center_code)
¶
Get a series that contains the center name for every participant.
All centers other than center_code are replaced by "Other Centers".
The output of this function can be nicely used with the histogram plot.
Parameters:
-
survey(LimeSurveyData) –The survey object
-
center_code(str) –ID of the center to filter by (like 'A01')
Returns:
Source code in src/survey_framework/data_analysis/analysis.py
get_data_for_q(survey, question_number)
¶
Returns a DataFrame with the responses for the given question ID.
Contingent questions (free text fields, shown as "other") are removed.
Deprecated
Use LimeSurveyData.get_responses(drop_other=True) instead.
Parameters:
-
survey(LimeSurveyData) –The LimeSurvey object
-
question_number(str) –The question ID (like 'A1')
Returns:
-
DataFrame–A DataFrame with all answers to the specified question
Source code in src/survey_framework/data_analysis/analysis.py
get_phd_duration(survey)
¶
Calculate relevant durations from questions A8 and A9.
We calculate: * How long has the participant been a doctoral researcher [years]? * How long do they estimate their project to last in total [months]?
Parameters:
-
survey(LimeSurveyData) –The survey object
Returns:
Source code in src/survey_framework/data_analysis/analysis.py
Scoring¶
Logic for converting answers on standardized scales into scores.
Condition
¶
rate_burnout(responses)
¶
Calculate burnout scores from participants' answers.
This uses the MBI-GS scale according to the Maslach Burnout Inventory (MBI) Manual, Fourth Edition.
Parameters:
-
responses(DataFrame) –responses to question D3d (burnout)
Returns:
-
DataFrame–SUM scores for each
Scale(3 ints) and a burnoutProfile(1 string)
Source code in src/survey_framework/data_analysis/scoring.py
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | |
rate_mental_health(responses, condition, keep_subscores=False)
¶
Calculate State/Trait Anxiety or Depression score based on responses to question.
Scoring is based on
- K. Kroenke, R. L. Spitzer, J. B. W. William, and B. Löwe., The Patient Health Questionnaire somatic, anxiety,and depressive symptom scales: a systematic review. General Hospital Psychiatry, 32(4):345-359, 2010.
- T. M. Marteau and H. Bekker., The development of a six-item short-form of the state scale of the spielberger state-trait anxiety inventory (STAI). British Journal of Clinical Psychology, 31(3):301-306, 1992.
Parameters:
-
responses(DataFrame) –DataFrame containing responses data
-
condition(Condition) –Which kind of mental health condition to rate
-
keep_subscores(bool, default:False) –Whether to include scores from subquestions in the output DataFrame, or only total score and classification. Default False.
Returns:
-
DataFrame–Mental health condition ratings ("score") and classifications ("class").
Source code in src/survey_framework/data_analysis/scoring.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | |
rate_satisfaction(responses, calc_average=True)
¶
Calculate satisfaction rating for each subquestion and calculate the average.
Uses a numeric scale from 1 = very dissatisfied to 5 = very satisfied.
Parameters:
-
responses(DataFrame) –DataFrame containing responses data
-
calc_average(bool, default:True) –Whether to calculate average satisfaction. Default True.
Returns:
-
DataFrame–Satisfaction ratings for each component (and overall average)
Source code in src/survey_framework/data_analysis/scoring.py
rate_somatic(responses, keep_subscores=False)
¶
Calculate Patient Health Questionaire (PHQ15) from participant responses.
Scoring is based on
- K. Kroenke, R. L. Spitzer, J. B. W. William, and B. Löwe., The Patient Health Questionnaire somatic, anxiety, and depressive symptom scales: a systematic review. General Hospital Psychiatry, 32(4):345-359, 2010.
Parameters:
-
responses(DataFrame) –DataFrame containing responses data
-
keep_subscores(bool, default:False) –Whether to include scores from subquestions in the output DataFrame, or only total score and classification.
Returns:
-
DataFrame–PHQ15 classifications in two columns ("D4_class" and "D4_score").
Source code in src/survey_framework/data_analysis/scoring.py
Bar Plots¶
Functions for basic bar plots.
plot_bar(survey, data_df, question, n_question, label_q_data='', orientation=Orientation.HORIZONTAL, stat=PlotStat.COUNT, width=6, height=4, bar_labels=BarLabels.NONE, bar_label_size=None, tick_label_size=None, tick_label_wrap=25)
¶
Plot bar plots (single and multiple).
Parameters:
-
survey(LimeSurveyData) –The LimeSurvey object
-
data_df(DataFrame) –DataFrame with responses to be plotted
-
question(str) –The question code
-
n_question(int) –Number of participants
-
label_q_data(str, default:'') –Label for axis with data from question.
-
orientation(Orientation, default:HORIZONTAL) –Plot orientation.
-
stat(PlotStat, default:COUNT) –Plot absolute values or percentages?
-
width(float, default:6) –Width of figure.
-
height(float, default:4) –Height of figure.
-
bar_labels(BarLabels, default:NONE) –How to format bar labels.
-
bar_label_size(int | None, default:None) –Font size for bar labels, if enabled.
-
tick_label_size(int | None, default:None) –Font size for tick labels.
-
tick_label_wrap(int, default:25) –How many characters are allowed per line in tick labels.
Returns:
-
tuple[Figure, Axes]–New matplotlib Figure and Axes for the bar plot.
Source code in src/survey_framework/plotting/barplots.py
plot_bar_comparison(survey, data_df, question, hue, hue_order=None, n_participants=None, label_q_data='', orient=Orientation.HORIZONTAL, stat=PlotStat.COUNT, width=6, height=4, bar_labels=BarLabels.NONE, bar_label_size=None, tick_label_size=None, tick_label_wrap=25)
¶
Plot comparison bar plots (single and multiple).
Parameters:
-
survey(LimeSurveyData) –The LimeSurvey object
-
data_df(DataFrame) –DataFrame with responses to be plotted
-
question(str) –Question code for the first question
-
hue(str) –Question code for the second question
-
hue_order(Sequence[str] | None, default:None) –Order of answer options for the second question.
-
n_participants(dict[Hashable, int] | None, default:None) –Number of participants per hue group (usually centers), or None to suppress printing N.
-
label_q_data(str, default:'') –Label for axis with data from question.
-
orient(Orientation, default:HORIZONTAL) –Plot orientation.
-
stat(PlotStat, default:COUNT) –Plot absolute values or percentages?
-
width(float, default:6) –Width of figure.
-
height(float, default:4) –Height of figure.
-
bar_labels(BarLabels, default:NONE) –How to format bar labels.
-
bar_label_size(int | None, default:None) –Font size for bar labels.
-
tick_label_size(int | None, default:None) –Font size for tick labels.
-
tick_label_wrap(int, default:25) –Number of letters after which tick labels wrap.
Returns:
-
tuple[Figure, Axes]–New matplotlib Figure and Axes for the bar plot.
Source code in src/survey_framework/plotting/barplots.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
Functions for side-by-side horizontal bar plots.
plot_bar_side_by_side(survey, data_left, data_right, y_left, y_right, stat=PlotStat.PERCENT, color_left=helmholtzblue, color_right=helmholtzgreen, title_left=None, title_right=None, width=12, height=10)
¶
Plot two horizontal bar plots side-by-side, sharing a common y axis.
Parameters:
-
survey(LimeSurveyData) –The survey object.
-
data_left(DataFrame) –Data for the left plot.
-
data_right(DataFrame) –Data for the right plot.
-
y_left(str) –Question ID (left)
-
y_right(str) –Question ID (right)
-
stat(PlotStat, default:PERCENT) –Which metric to plot (percent / count)
-
color_left(str, default:helmholtzblue) –Bar color (left).
-
color_right(str, default:helmholtzgreen) –Bar color (right).
-
title_left(str | None, default:None) –Left plot title.
-
title_right(str | None, default:None) –Right plot title.
-
width(float, default:12) –Total plot width.
-
height(float, default:10) –Total plot height.
Returns:
Source code in src/survey_framework/plotting/barplots_sidebyside.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | |
plot_sidebyside_comparison_singleQ(survey, data_left, data_right, base_q_left, base_q_right, comp_q, N_left, N_right, title_left='', title_right='', width=12, height=10, fontsize=10, plot_stat=PlotStat.COUNT, bar_labels=BarLabels.NONE, fontsize_bar_labels=10, text_wrap=25)
¶
Plot two barplots side by side, with an additional grouping given by comp_q.
Parameters:
-
survey(LimeSurveyData) –The main survey object
-
data_left(DataFrame) –Data for the left question
-
data_right(DataFrame) –Data for the right question
-
base_q_left(str) –Question code for the left question
-
base_q_right(str) –Question code for the right question
-
comp_q(str) –Question code that is used as a grouper (hue) for both questions
-
N_left(int) –Size of the left population
-
N_right(int) –Size of the right population
-
title_left(str, default:'') –Title for the left plot
-
title_right(str, default:'') –Title for the right plot
-
width(float, default:12) –Total width of the plot
-
height(float, default:10) –Total height of the plot
-
fontsize(int, default:10) –Font size for titles and axis (tick) labels
-
plot_stat(PlotStat, default:COUNT) –Whether to plot absolute (PERCENT) or relative (COUNT)
-
bar_labels(BarLabels, default:NONE) –Whether to label each bar
-
fontsize_bar_labels(int, default:10) –Font size for the bar labels, if enabled above
-
text_wrap(int, default:25) –After how many characters axis and legend labels should wrap
Returns:
Source code in src/survey_framework/plotting/barplots_sidebyside.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 | |
Stacked Bar Plots¶
Stacked bar plots. This is very quick-and-dirty and needs a proper cleanup.
plot_stacked_bar_categorical(df, classes_column, category_column, na_values=False, label_q_data='', width=6, height=4, fontsize=None, fontsize_axes_labels=None, legend_title='', category_order=None)
¶
Plot a stacked barplot with an arbitrary number of bars.
This might be what we want instead of the above -- Code needs a cleanup and proper documentation though.
Parameters:
-
df(DataFrame) –description
-
classes_column(str) –description
-
category_column(str) –description
-
na_values(bool, default:False) –description
-
label_q_data(str, default:'') –description
-
width(int, default:6) –description
-
height(int, default:4) –description
-
fontsize(int | None, default:None) –description
-
fontsize_axes_labels(int | None, default:None) –description
-
legend_title(str, default:'') –description
-
category_order(list[str] | None, default:None) –description
Returns:
-
tuple[Figure, Axes]–New matplotlib figure and axes.
Source code in src/survey_framework/plotting/stacked.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | |
plot_stacked_bar_comparison(df1, df2, col_of_interest, plot_title, order, legend_loc, group_labels=('Group 1', 'Group 2'), colors=None, width=3, height=4, ax=None, n_y_pos=0.95)
¶
Create a vertical stacked bar plot of mental health classes for two groups.
Parameters:
-
df1(DataFrame) –DataFrame for group 1 (left bar).
-
df2(DataFrame) –DataFrame for group 2 (right bar).
-
col_of_interest(str) –Data column to plot (stacked)
-
plot_title(str) –Heading for this plot
-
order(list[str]) –Ordered list of categories for stacked bars and legend.
-
legend_loc(Literal['top', 'right', 'bottom'] | None) –Position of the legend, or None for no legend.
-
group_labels(tuple[str, str], default:('Group 1', 'Group 2')) –Tuple of group labels.
-
colors(list[list[tuple[float, float, float]]] | None, default:None) –Optional list of colors (auto-generated from helmholtzcolors if None).
-
width(float, default:3) –Width of the plot.
-
height(float, default:4) –Height of the plot.
-
ax(Axes | None, default:None) –Axes to draw the plot on. Generate a new Axes if None (default).
-
n_y_pos(float, default:0.95) –vertical position of the N labels (default: 95% plot height)
Returns:
-
tuple[Figure, Axes]–Matplotlib figure and axis.
Source code in src/survey_framework/plotting/stacked.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | |
plot_stacked_bar_single(df1, col_of_interest, plot_title, order, legend_loc, colors=None, width=3, height=4, ax=None, n_y_pos=0.95)
¶
Create a vertical stacked bar plot of mental health classes for one group.
NOTE: This is a quick-fix. It might make sense to merge it with histplot.py/simple_histplot() where stacking should be implemented anyway
Parameters:
-
df1(DataFrame) –DataFrame for group 1 (left bar).
-
col_of_interest(str) –Data column to plot (stacked)
-
plot_title(str) –Heading for this plot
-
order(list[str]) –Ordered list of categories for stacked bars and legend.
-
legend_loc(Literal['top', 'right', 'bottom'] | None) –Position of the legend, or None for no legend.
-
colors(list[list[tuple[float, float, float]]] | None, default:None) –Optional list of colors (auto-generated from helmholtzcolors if None).
-
width(float, default:3) –Width of the plot.
-
height(float, default:4) –Height of the plot.
-
ax(Axes | None, default:None) –Axes to draw the plot on. Generate a new Axes if None (default).
-
n_y_pos(float, default:0.95) –vertical position of the N labels (default: 95% plot height)
Returns:
-
tuple[Figure, Axes]–Matplotlib figure and axis.
Source code in src/survey_framework/plotting/stacked.py
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | |
Special Plots¶
Survival Plots. Typically used to visualize change over time.
plot_survival_plot(df, category=None, ticks=None, tick_map=str, legend_replace=None, legend_title=None, colors=None, width=6, height=4)
¶
Plots the given DataFrame as a survival plot, approaching zero.
Parameters:
-
df(DataFrame) –DataFrame with a column of numerical data called "data".
-
category(str | None, default:None) –Column in
dfto categorize the data. -
ticks(Iterable[int] | None, default:None) –Iterable of x axis ticks.
-
tick_map(Callable[[int], str], default:str) –Function to generate strings from ticks.
-
legend_replace(dict[str, str] | None, default:None) –Replacements for legend entries.
-
legend_title(str | None, default:None) –Heading for the legend.
-
colors(list[tuple[float, float, float]] | None, default:None) –Line colors, instead of shades of blue.
-
width(int, default:6) –Horizontal figure size.
-
height(int, default:4) –Vertical figure size.
Returns:
-
tuple[Figure, Axes]–The matplotlib figure and axes.
Source code in src/survey_framework/plotting/survivalplot.py
Likert Plots (typically used for data on a 5-point scale).
plot_likertplot(survey, data_df, question, order, bar_labels=BarLabels.PERCENT, width=6, height=4, percent_cutoff=8, text_wrap=30, relabel_subquestions=True)
¶
Plot the given data as a Likert plot.
Parameters:
-
survey(LimeSurveyData) –the LimeSurvey object
-
data_df(DataFrame) –dataframe containing answers to be plotted
-
question(str) –question code (e.g. 'D4')
-
order(list[str]) –ordered list of answer options. The rest will be dropped!
-
bar_labels(BarLabels, default:PERCENT) –which kind of bar labels to use.
-
width(float, default:6) –width of the figure.
-
height(float, default:4) –height of the figure.
-
percent_cutoff(int, default:8) –If groups are smaller than x percent, they don't get a label.
-
text_wrap(int, default:30) –wrap question labels after x characters.
-
relabel_subquestions(bool, default:True) –Whether to rewrite y axis labels using the question data.
Returns:
-
tuple[Figure, Axes]–The matplotlib figure and axis
Source code in src/survey_framework/plotting/likertplot.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | |
A heatmap, used to visualize correlation strength.
plot_heatmap(df, survey, width=6.5, height=6, method=CorrMethod.SPEARMAN)
¶
Correlation heatmap of the input dataframe vs. all (mental) health scores.
Parameters:
-
df(DataFrame) –Dataframe with numeric columns that should be correlated against health
-
survey(LimeSurveyData) –main survey object
-
width(float, default:6.5) –Horizontal figure size.
-
height(float, default:6) –Vertical figure size.
-
method(CorrMethod, default:SPEARMAN) –Statistical correlation method.
Returns:
-
tuple[Figure, Axes]–tuple of matplotlib figure and axes for the heatmap
Source code in src/survey_framework/plotting/heatmap.py
A very simple, but versatile histogram plot.
This basically produces bar plots, but can add extras like a density curve.
simple_histplot(data_df, question_code, order_dict, hue_series=None, hue_order=None, kde=False, log_scale=False, binwidth=None, width=10, height=6, bar_labels=BarLabels.NONE)
¶
Plot a histogram of values in data_df[question_code].
Currently in experimental state, to be expanded for stacked barplots?
Parameters:
-
data_df(DataFrame) –DataFrame to be plotted
-
question_code(str) –Column in
data_dfto be plotted -
order_dict(dict[str, list[str]]) –answer ordering, can be empty (ORDER from order/order2024.py)
-
hue_series(Series[str] | None, default:None) –Separator for data_df (needs same index).
-
hue_order(Sequence[str] | None, default:None) –How to sort hues in the legend and plot
-
kde(bool, default:False) –Whether to plot a density curve.
-
log_scale(bool, default:False) –whether the y axis should be log-scaled.
-
binwidth(int | None, default:None) –Width of bins; automatically inferred if not given.
-
width(float, default:10) –Plot width.
-
height(float, default:6) –Plot height.
-
bar_labels(BarLabels, default:NONE) –How to label each bar (NONE by default, or PERCENT)
Returns:
-
tuple[Figure, Axes]–New figure and axes of the histogram
Source code in src/survey_framework/plotting/histplot.py
Sankey Plot -- visualizes the "flow" of participants between questions.
plot_sankey(data_df, titles=None, title='', width=6, height=8, fontsize=None, plot_fractions=True)
¶
Plots a two staged sankey diagram.
Parameters:
-
data_df(DataFrame) –Data containing rows like (label_left, count, label_right, same_count)
-
titles(list[str] | None, default:None) –Titles of both stages.
-
title(str, default:'') –deprecated, unused
-
width(float, default:6) –Total plot width.
-
height(float, default:8) –Total plot height.
-
fontsize(int | None, default:None) –Font size for the plot
-
plot_fractions(bool, default:True) –Whether group sizes should be displayed
Returns:
-
Figure–New Figure and Axes