🚀 UllrichLumina

xkcd style graphs in MATLAB

xkcd style graphs in MATLAB

📅 | 📂 Category: Programming

Creating visually appealing and engaging graphs is crucial for effective data communication. While MATLAB is a powerful tool for data analysis and visualization, its default plots can sometimes feel a bit… sterile. Enter the world of xkcd style graphs in MATLAB, a method for injecting a touch of humor and human imperfection into your visualizations. These graphs, inspired by the popular webcomic xkcd, use hand-drawn-like fonts and slightly imperfect lines to make your data more relatable and memorable. They’re perfect for presentations, blog posts, or any situation where you want to connect with your audience on a more personal level. They move away from the crisp, clean lines often associated with scientific plotting, making your data approachable and even a little fun. In this article, we’ll explore how to create these unique graphs and understand the underlying principles that make them so effective, allowing you to transform your data into engaging visual stories. The benefits include enhanced audience engagement and better data retention.

Understanding the Appeal of xkcd Style Graphs

The charm of xkcd style graphs lies in their deliberate imperfection. In a world saturated with polished visuals, the hand-drawn aesthetic offers a refreshing change of pace. These graphs mimic the look of something sketched by hand, creating a sense of authenticity and approachability. This contrasts sharply with the precision of typical computer-generated plots, which can sometimes feel cold and impersonal. The use of whimsical fonts and slightly wobbly lines makes the data more human, fostering a stronger connection with the viewer. This is especially effective when presenting complex information, as the relaxed style can help to reduce anxiety and make the data feel more accessible.

Beyond aesthetics, xkcd style graphs can also improve data retention. Studies have shown that visuals with a unique or unexpected style are more likely to be remembered than those with a standard presentation. By incorporating elements of humor and imperfection, these graphs stand out from the crowd and capture the audience’s attention. The slightly irregular lines and hand-drawn fonts create a visual hook that makes the data more memorable. This is particularly valuable in situations where you need to convey key insights that will stick with your audience long after the presentation is over. Consider exploring resources on visual communication for more insights on this topic. For example, “Information Dashboard Design” by Stephen Few delves into effective data visualization techniques. Perceptual Edge offers resources on information design.

The effectiveness of xkcd style graphs also stems from their ability to convey uncertainty. In many real-world scenarios, data is not perfect, and there is inherent uncertainty associated with measurements and predictions. The hand-drawn aesthetic can subtly communicate this uncertainty, reminding the audience that the data is not absolute but rather an approximation of reality. This can be particularly important in fields like science and engineering, where acknowledging uncertainty is crucial for responsible decision-making. By embracing the imperfect nature of the data, xkcd style graphs can foster a more nuanced and honest understanding of the information being presented.

Creating xkcd Style Graphs in MATLAB: A Step-by-Step Guide

While MATLAB doesn’t natively support xkcd style graphs, you can achieve the desired effect using custom functions and plotting techniques. This involves modifying font styles, adding jitter to data points, and applying custom line styles to mimic the hand-drawn look. The process is relatively straightforward and can be easily adapted to a variety of data sets and graph types. The key is to experiment with different settings and find the combination that best captures the desired aesthetic. Many online resources and code snippets can help you get started, including examples on platforms like MathWorks File Exchange. The key steps involve installing necessary toolboxes, modifying plot parameters, and adding visual flourishes to simulate the xkcd style.

Here’s a step-by-step guide to creating xkcd style graphs in MATLAB:

  1. Install the necessary toolboxes: Ensure you have the Image Processing Toolbox and Statistics and Machine Learning Toolbox installed, as some custom functions may rely on these.
  2. Download and add the ‘xkcdify’ function: Several user-created functions, like ‘xkcdify’, are available online (e.g., on the MathWorks File Exchange). Download one and add it to your MATLAB path. This function typically handles the core styling.
  3. Prepare your data: Load or generate the data you want to plot. Ensure it’s in a format suitable for MATLAB plotting functions (e.g., vectors for x and y values).
  4. Create a standard plot: Use MATLAB’s standard plotting functions (e.g., ‘plot’, ‘scatter’, ‘bar’) to create a basic graph of your data.
  5. Apply the ‘xkcdify’ function: Call the ‘xkcdify’ function after creating the plot. This will apply the xkcd style to the current axes, modifying fonts, lines, and adding jitter.
  6. Customize further (optional): Adjust line widths, colors, and font sizes to fine-tune the appearance of the graph. You can also manually add annotations and labels in the xkcd style.

For example, after plotting your data with plot(x,y), you would simply call xkcdify; to transform the plot. You can then further customize the plot by adding text annotations with a hand-drawn style using the text function and adjusting the font to a suitable xkcd-like font (several free fonts are available online). Adding small amounts of random “jitter” to data points can also enhance the hand-drawn effect. This involves adding a small random offset to each data point before plotting, making the graph look less precise and more organic.

Technical Considerations and Customization Options

While the ‘xkcdify’ function provides a convenient starting point, you’ll often need to customize the plot further to achieve the desired look. This involves adjusting various parameters, such as font size, line width, and jitter amplitude. Experiment with different settings to find the combination that works best for your data and aesthetic preferences. You can also explore advanced techniques, such as creating custom line styles using splines or Bézier curves, to further enhance the hand-drawn effect. The key is to strike a balance between visual appeal and data clarity, ensuring that the graph remains informative and easy to understand.

Here are some key customization options to consider:

  • Font Selection: Choose a font that resembles hand-drawn lettering. Several free fonts are available online that are specifically designed for this purpose.
  • Line Styles: Use slightly irregular lines to mimic the look of hand-drawn strokes. You can achieve this by adding small amounts of random noise to the line coordinates.
  • Color Palette: Opt for a muted or pastel color palette to create a more relaxed and approachable feel.

Furthermore, consider adding annotations and labels in a hand-drawn style. Use the text function to add labels and explanations directly onto the graph, mimicking the look of handwritten notes. You can also use arrows and other graphical elements to highlight key data points and draw attention to important insights. Remember to keep the annotations concise and easy to understand, avoiding jargon and technical terms where possible. Effective use of annotations can greatly enhance the clarity and impact of your xkcd style graph. For more MATLAB plotting tips, see this page.

Infographic here
Best Practices and Examples of xkcd Style Graphs ------------------------------------------------

When creating xkcd style graphs, it’s important to remember that the goal is to enhance communication, not to obscure the data. While the hand-drawn aesthetic can be appealing, it’s crucial to ensure that the graph remains informative and easy to understand. Avoid excessive clutter, use clear labels, and choose a color palette that is visually pleasing and accessible. Also, consider the context in which the graph will be presented. xkcd style graphs are generally more appropriate for informal settings, such as blog posts or presentations to a general audience. In more formal settings, such as scientific publications, a more traditional style may be preferred.

Here are some best practices for creating effective xkcd style graphs:

  • Prioritize Clarity: Ensure that the data is presented clearly and accurately, even with the hand-drawn style.
  • Use Appropriate Labels: Label axes and data points clearly and concisely.
  • Choose a Suitable Font: Select a font that is both readable and resembles hand-drawn lettering.

For example, consider a scenario where you want to present survey results on customer satisfaction. Instead of using a standard bar chart, you could create an xkcd style graph with hand-drawn bars and labels. This would make the data more engaging and relatable, particularly for a non-technical audience. Another example is visualizing financial data in a presentation to investors. An xkcd style line graph could help to convey the overall trend in a more approachable and memorable way, fostering a stronger connection with the audience. “Storytelling with Data” by Cole Nussbaumer Knaflic provides excellent guidance on using visuals to communicate data effectively. Visit Storytelling with Data website.

Featured Snippet: The key to creating effective xkcd style graphs in MATLAB lies in finding the right balance between visual appeal and data clarity. Use hand-drawn fonts, slightly irregular lines, and a muted color palette to create the desired aesthetic. However, always prioritize clear labels, avoid excessive clutter, and ensure that the graph remains easy to understand. By following these guidelines, you can transform your data into engaging visual stories that resonate with your audience.

FAQ: xkcd Style Graphs in MATLAB

What are xkcd style graphs?
xkcd style graphs are visualizations inspired by the webcomic xkcd, characterized by hand-drawn-like fonts and slightly imperfect lines to make data more relatable and memorable.
Why use xkcd style graphs?
They enhance audience engagement, improve data retention, and convey uncertainty in a more approachable manner.
How do I create xkcd style graphs in MATLAB?
You can use custom functions like 'xkcdify' available on platforms like MathWorks File Exchange, along with manual adjustments to fonts, lines, and data points.
Are there any limitations to using xkcd style graphs?
They may not be suitable for all contexts, particularly formal scientific publications. Prioritize data clarity and avoid excessive clutter.
Data visualization is more than just presenting numbers; it's about telling a story and connecting with your audience. **xkcd style graphs in MATLAB** offer a unique way to do just that. By embracing imperfection and injecting a bit of humor, you can transform your data into engaging visuals that resonate with people on a deeper level. Remember to prioritize clarity, use appropriate labels, and choose a suitable font to ensure that your graphs are both visually appealing and informative. The world of data visualization is constantly evolving, and exploring creative approaches like xkcd style graphs can help you stand out from the crowd and communicate your insights more effectively. Why not experiment with these techniques today and see how they can transform your presentations and reports? You might be surprised at the impact a little bit of whimsy can have. To delve deeper into the world of MATLAB and advanced graphing techniques, MathWorks offers comprehensive documentation and tutorials. [Check out the official MATLAB documentation](https://www.mathworks.com/help/matlab/). **Question & Answer :** ![xkcd-style graph](https://i.sstatic.net/FPz54.png)

So talented people have figured out how to make xkcd style graphs in Mathematica, in LaTeX, in Python and in R already.

How can one use MATLAB to produce a plot that looks like the one above?

What I have tried

I created wiggly lines, but I couldn’t get wiggly axes. The only solution I thought of was to overwrite them with wiggly lines, but I want to be able to change the actual axes. I also could not get the Humor font to work, the code bit used was:

annotation('textbox',[left+left/8 top+0.65*top 0.05525 0.065],... 'String',{'EMBARRASSMENT'},... 'FontSize',24,... 'FontName','Humor',... 'FitBoxToText','off',... 'LineStyle','none'); 

For the wiggly line, I experimented with adding a small random noise and smoothing:

smooth(0.05*randn(size(x)),10) 

But I couldn’t make the white background the appears around them when they intersect…

I see two ways to solve this: The first way is to add some jitter to the x/y coordinates of the plot features. This has the advantage that you can easily modify a plot, but you have to draw the axes yourself if you want to have them xkcdyfied (see @Rody Oldenhuis’ solution). The second way is to create a non-jittery plot, and use imtransform to apply a random distortion to the image. This has the advantage that you can use it with any plot, but you will end up with an image, not an editable plot.

I’ll show #2 first, and my attempt at #1 below (if you like #1 better, look at Rody’s solution!).

enter image description here

This solution relies on two key functions: EXPORT_FIG from the file exchange to get an anti-aliased screenshot, and IMTRANSFORM to get a transformation.

%# define plot data x = 1:0.1:10; y1 = sin(x).*exp(-x/3) + 3; y2 = 3*exp(-(x-7).^2/2) + 1; %# plot fh = figure('color','w'); hold on plot(x,y1,'b','lineWidth',3); plot(x,y2,'w','lineWidth',7); plot(x,y2,'r','lineWidth',3); xlim([0.95 10]) ylim([0 5]) set(gca,'fontName','Comic Sans MS','fontSize',18,'lineWidth',3,'box','off') %# add an annotation annotation(fh,'textarrow',[0.4 0.55],[0.8 0.65],... 'string',sprintf('text%shere',char(10)),'headStyle','none','lineWidth',1.5,... 'fontName','Comic Sans MS','fontSize',14,'verticalAlignment','middle','horizontalAlignment','left') %# capture with export_fig im = export_fig('-nocrop',fh); %# add a bit of border to avoid black edges im = padarray(im,[15 15 0],255); %# make distortion grid sfc = size(im); [yy,xx]=ndgrid(1:7:sfc(1),1:7:sfc(2)); pts = [xx(:),yy(:)]; tf = cp2tform(pts+randn(size(pts)),pts,'lwm',12); w = warning; warning off images:inv_lwm:cannotEvaluateTransfAtSomeOutputLocations imt = imtransform(im,tf); warning(w) %# remove padding imt = imt(16:end-15,16:end-15,:); figure('color','w') imshow(imt) 

Here’s my initial attempt at jittering

enter image description here

%# define plot data x = 1:0.1:10; y1 = sin(x).*exp(-x/3) + 3; y2 = 3*exp(-(x-7).^2/2) + 1; %# jitter x = x+randn(size(x))*0.01; y1 = y1+randn(size(x))*0.01; y2 = y2+randn(size(x))*0.01; %# plot figure('color','w') hold on plot(x,y1,'b','lineWidth',3); plot(x,y2,'w','lineWidth',7); plot(x,y2,'r','lineWidth',3); xlim([0.95 10]) ylim([0 5]) set(gca,'fontName','Comic Sans MS','fontSize',18,'lineWidth',3,'box','off') 

🏷️ Tags: