<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Syed Hamed Raza on Medium]]></title>
        <description><![CDATA[Stories by Syed Hamed Raza on Medium]]></description>
        <link>https://medium.com/@ai.mlresearcher?source=rss-a9253868464d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aws2Bnoq2Z7G4v0Z38IBbA.jpeg</url>
            <title>Stories by Syed Hamed Raza on Medium</title>
            <link>https://medium.com/@ai.mlresearcher?source=rss-a9253868464d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:06:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ai.mlresearcher/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Data to Insight: Mastering Visualization with the Grammar of Graphics]]></title>
            <link>https://medium.com/@ai.mlresearcher/from-data-to-insight-mastering-visualization-with-the-grammar-of-graphics-bf68134aaa10?source=rss-a9253868464d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf68134aaa10</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ggplot2]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[grammar-of-graphics]]></category>
            <dc:creator><![CDATA[Syed Hamed Raza]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 13:51:57 GMT</pubDate>
            <atom:updated>2026-04-09T13:51:57.722Z</atom:updated>
            <content:encoded><![CDATA[<h4>Principles, Grammar, and Practice with ggplot2 and Beyond</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DHUaf008bW7MRhgU" /><figcaption>Photo by <a href="https://unsplash.com/@goumbik?utm_source=medium&amp;utm_medium=referral">Lukas Blazek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data visualization is a critical part of any data science project. Once data have been imported and wrangled into place, visualizing your data can help you get a handle on what’s going on in the dataset. Similarly, once you’ve completed your analysis and are ready to present your findings, data visualizations are a highly effective way to communicate your results to others. In this course we will cover what data visualization is and define some of the basic types of data visualizations.</p><p>In this course you will learn about the ggplot2 R package, a powerful set of tools for making stunning data graphics that has become the industry standard. You will learn about different types of plots, how to construct effect plots, and what makes for a successful or unsuccessful visualization.</p><h3>1. General Features of Plots</h3><p>Good plots have a number of features. While not exhaustive, good plots have:</p><ol><li>Clearly-labeled axes.</li><li>Text that are large enough to see.</li><li>Axes that are not misleading.</li><li>Data that are displayed appropriately considering the type of data you have.</li></ol><p>More specifically, however, there are two general approaches to data visualization: <strong>exploratory plots</strong> and <strong>explanatory plots</strong>.</p><h4>1.1 Exploratory Plots</h4><p>These are <strong>data displays to help you better understand and discover hidden patterns in the data</strong> you’re working with. These won’t be the prettiest plots, but they will be incredibly helpful. Exploratory visualizations have a number of general characteristics:</p><ul><li>They are made quickly.</li><li>You’ll make a large number of them.</li><li>The axes and legends are cleaned up.</li></ul><p>Below we have a graph where the axes are labeled and general pattern can be determined. This is a great example of an exploratory plot. It lets you the analyst know what’s going on in your data, but it isn’t yet ready for a big presentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*ozJgjd-kjtqWct7j" /></figure><p><em>Figure: Exploratory Plot</em></p><p>As you’re trying to understand the data you have on hand, you’ll likely make a lot of plots and tables just to figure out to explore and understand the data. Because there are a lot of them and they’re for your use (rather than for communicating with others), you don’t have to spend all your time making them perfect. But, you do have to spend enough time to make sure that you’re drawing the right conclusions from this. Thus, you don’t have to spend a long time considering what colors are perfect on these, but you do want to make sure your axes are not cut off.</p><p>Other Exploratory Plotting Examples: <a href="https://blog.datazar.com/exploratory-data-analysis-using-r-part-i-17e4e8e03961">Air Quality Data</a></p><h4>1.2 Explanatory Plots</h4><p>These are data displays that aim to <strong>communicate insights to others</strong>. These are plots that you spend a lot of time making sure they’re easily interpretable by an audience. General characteristics of explanatory plots:</p><ul><li>They take a while to make.</li><li>There are only a few of these for each project.</li><li>You’ve spent a lot of time making sure the colors, labels, and sizes are all perfect for your needs.</li></ul><p>Here we see an improvement upon the exploratory plot we looked at previously. Here, the axis labels are more descriptive. All of the text is larger. The legend has been moved onto the plot. The points on the plot are larger. And, there is a title. All of these changes help to improve the plot, making it an explanatory plot that would be presentation-ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*A0yp9ilzip_1mqo4" /></figure><p><em>Figure: Explanatory Plots</em></p><p>Explanatory plots are made after you’ve done an analysis and once you really understand the data you have. The goal of these plots is to communicate your findings clearly to others. To do so, you want to make sure these plots are made carefully — the axis labels should all be clear, the labels should all be large enough to read, the colors should all be carefully chosen, etc.. As this takes times and because you do not want to overwhelm your audience, you only want to have a few of these for each project. We often refer to these as “publication ready” plots. These are the plots that would make it into an article at the New York Times or in your presentation to your bosses.</p><h3>2. Plot Types</h3><p>Above we saw data displayed as both an exploratory plot and an explanatory plot. That plot was an example of a scatterplot. However, there are many types of plots that are helpful. We’ll discuss a few basic ones below and will include links to a few galleries where you can get a sense of the many different types of plots out there.</p><p>To do this, we’ll use the “Davis” dataset which includes, height and weight information for 200 people.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*A9daGcaqRQwKRTip" /></figure><p><em>Figure: Dataset</em></p><h4>2.1 Histogram</h4><p>Histograms are helpful when you want to <strong>better understand what values you have in your dataset for a single set of numbers</strong>. For example, if you had a dataset with information about many people, you may want to know how tall the people in your dataset are. To quickly visualize this, you could use a histogram. Histograms let you know what range of values you have in your dataset. For example, below you can see that in this dataset, the height values range from around 50 to around 200 cm. The shape of the histogram also gives you information about the individuals in your dataset. The number of people at each height are also counted. So, the tallest bars show that there are about 40 people in the dataset whose height is between 165 and 170 cm. Finally, you can quickly tell, at a glance that most people in this dataset are at least 150 cm tall, but that there is at least one individually whose reported height is much lower.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*ZDGSq9_RJ0WpeI3n" /></figure><p><em>Figure: Histogram</em></p><h4>2.2 Densityplot</h4><p>Densityplots are smoothed versions of histograms, visualizing the distribution of a continuous variable. These plots effectively visualize the distribution shape and are, unlike histograms, are not sensitive to the number of bins chosen for visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*pn1-Qho0fVfxuOpD" /></figure><p><em>Figure: Densityplot</em></p><h4>2.3 Scatterplot</h4><p>Scatterplots are helpful when you have <strong>numerical values for two different pieces of information</strong> and you want to understand the relationship between those pieces of information. Here, each dot represents a different person in the dataset. The dot’s position on the graph represents that individual’s height and weight. Overall, in this dataset, we can see that, in general, the more someone weighs, the taller they are. Scatterplots, therefore help us at a glance better understand the relationship between two sets of numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*JkVrBd5EJ_XH9pYo" /></figure><p><em>Figure: Scatterplot</em></p><h4>2. 4 Barplot</h4><p>When you only have <strong>a single categorical variable that you want broken down and quantified by category</strong>, a barplot will be ideal. For example if you wanted to look at how many females and how many males you have in your dataset, you could use a barplot. The comparison in heights between bars clearly demonstrates that there are more females in this dataset than males.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*f0qUw6Bjupq5FuDw" /></figure><p><em>Figure: Barplot</em></p><h4>2.4.1 Grouped Barplot</h4><p>Grouped barplots, like simple barplots, demonstrate the counts for a group; however, they break this down by an additional categorical variable. For example, here we see the number of individuals within each % category along the x-axis. But, these data are further broken down by gender (an additional categorical variable). Comparisons between bars that are side-by-side are made most easily by our visual system. So, it’s important to ensure that the bars you want viewers to be able to compare most easily are next to one another in this plot type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*5_nemtVn9sivyuga" /></figure><p><em>Figure: Grouped Barplot</em></p><h4>2.4.2 Stacked Barplot</h4><p>Another common variation on barplots are stacked barplots. Stacked barplots take the information from a grouped barplot but stacks them on top of one another. This is most helpful when the bars add up to 100%, such as in a survey response where you’re measuring percent of respondents within each category. Otherwise, it can be hard to compare between the groups within each bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*XlFDmvgOAg1JC4BL" /></figure><p><em>Figure: Stacked barplot</em></p><h4>2.5 Boxplot</h4><p>Boxplots also summarize <strong>numerical values across a category</strong>; however, instead of just comparing the heights of the bar, they give us an idea of the range of values that each category can take. For example, if we wanted to compare the heights of men to the heights of women, we could do that with a boxplot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*9zkJt-2_v886H33B" /></figure><p><em>Figure: Boxplot</em></p><p>To interpret a boxplot, there are a few places where we’ll want to focus our attention. For each category, the horizontal line through the middle of the box corresponds to the median value for that group. So, here, we can say that the median, or most typical height for females is about 165 cm. For males, this value is higher, just under 180 cm. Outside of the colored boxes, there are dashed lines. The ends of these lines correspond to the typical range of values. Here, we can see that females tend to have heights between 150 and 180cm. Lastly, when individuals have values outside the typical range, a boxplot will show these individuals as circles. These circles are referred to as outliers.</p><h4>2.6 Line Plots</h4><p>The final type of basic plot we’ll discuss here are line plots. Line plots are most effective at showing a <strong>quantitative trend over time</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*6PCyeTaOCv-e22SA" /></figure><p><em>Figure: Line Plot</em></p><h3>3. Choose the Right Type of Plot</h3><p>If your goal is to allow the viewer to compare values across groups, pie charts should largely be avoided. This is because it’s easier for the human eye to differentiate between bar heights than it is between similarly-sized slices of a pie. Thinking about the best way to visualize your data before making the plot is an important step in the process of data visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*czw5Z_rxQcn4GtxU" /></figure><p><em>Figure: Choose an appropriate plot for the data you’re visualizing.</em></p><h4>3.1 Be Mindful When Choosing Colors</h4><p>Choosing colors that work for the story you’re trying to convey with your visualization is important. Avoiding colors that are hard to see on a screen or when projected, such as pastels, is a good idea. Additionally, red-green color blindness is common and leads to difficulty in distinguishing reds from greens. Simply avoiding making comparisons between these two colors is a good first step when visualizing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*KkQm6Qd4ovsSPF6u" /></figure><p><em>Figure: Choosing appropriate colors for visualizations is important</em></p><p>Beyond red-green color blindness, there is an entire group of experts out there in color theory.To learn more about available <a href="https://github.com/EmilHvitfeldt/r-color-palettes">color palettes in R</a> or to read more from a pro named Lisa Charlotte Rost <a href="https://lisacharlotterost.github.io/2016/04/22/Colors-for-DataVis/">talking about color choices in data visualization</a>, feel free to read more.</p><h4>3.2 Label the Axes</h4><p>Whether you’re making an exploratory or explanatory visualization, labeled axes are a must. They help tell the story of the figure. Making sure the axes are clearly labeled is also important. Rather than labeling the graph below with “h” and “g,” we chose the labels “height” and “gender,” making it clear to the viewer exactly what is being plotted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*MiRSwarUDKXXO1ac" /></figure><p><em>Figure: Having descriptive labels on your axes is critical</em></p><h4>3.3 Make Sure the Numbers Add Up</h4><p>When you’re making a plot that should sum to 100, make sure that it in fact does. Taking a look at visualizations after you make them to ensure that they make sense is an important part of the data visualization process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*DHTRQw7Iels4x-sU" /></figure><p><em>Figure: At left, the pieces of the pie only add up to 95%. On the right, this error has been fixed and the pieces add up to 100%</em></p><h4>3.4 Make Sure the Numbers and Plots Make Sense Together</h4><p>Another common error is having labels that don’t reflect the underlying graphic. For example, here, we can see on the left that the turquoise piece is more than half the graph, and thus the label 45% must be incorrect. At right, we see that the labels match what we see in the figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*WOJh5wF2T68D-Bfo" /></figure><p><em>Figure: Checking to make sure the numbers and plot make sense together is important</em></p><h4>3.5 Make Comparisons Easy on Viewers</h4><p>There are many ways in which you can make comparisons easier on the viewer. For example, avoiding unnecessary whitespace between the bars on your graph can help viewers make comparisons between the bars on the barplot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*r45PJ7nkcJk1OZOR" /></figure><p><em>Figure: At left, there is extra white space between the bars of the plot that should be removed. On the right, we see an improved plot</em></p><h4>3.6 Use y-axes That Start at Zero</h4><p>Often, in an attempt to make differences between groups look larger than they are, y-axis will be started at a value other than zero. This is misleading. Y-axis for numerical information should start at zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*X4goMlnT-y-qaVe5" /></figure><p><em>Figure: At left, the differences between the vars appears larger than on the right; however, this is just because the y-axis starts at 200. The proper way to start this graph is to start the y-axis at 0.</em></p><h4>3.7 Keep It Simple</h4><p>The goal of data visualization is to improve understanding of data. Sometimes complicated visualizations cannot be avoided; however, when possible, keep it simple.</p><p>Here, the graphic does not immediately convey a main point. It’s hard to interpret what each circle means or what the story of this graphic is supposed to me. Make sure in your graphics that your main point comes through:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*dj2GOxS-VdQYqPez" /></figure><p><em>Figure: Main point unclear</em></p><p>Similarly, the intention of your graphic should never be to mislead and confuse. Unlike what was done here, be sure that your data visualizations improve viewers’ understanding. Do not aim to confuse:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*9teEqv4A4Q5BhIof" /></figure><p><em>Figure: Confusion is conveyed here</em></p><h3>4. Three Questions You Should Ask</h3><h4>4.1 What’s your point?</h4><p>Whenever you have data you’re trying to plot, think about what you’re actually trying to show. Once you’ve taken a look at your data, a good title for the plot can be helpful. Your title should <strong>tell viewers what they’ll see when they look at the plot</strong>.</p><h4>4.2 How can you emphasize your point in your chart?</h4><p>We talked about it in the last lesson, but an incredibly important decision is choosing an appropriate chart for the type of data you have. In the next section of this lesson, we’ll discuss what type of data are appropriate for each type of plot in R; however, for now, we’ll just focus on an iPhone data example. With this example, we’ll discuss that you can emphasize your point by:</p><ul><li>Adding data</li><li>Highlighting data with color</li><li>Annotating your plot</li></ul><h4>4.3 Adding data</h4><p>In any plot that makes a specific claim, it’s usually important to show additional data as a reference for comparison. For example, if you were making a plot of that suggests that the iPhone has been Apple’s most successful product, it would be helpful for the plot to compare iPhone sales with other Apple products, say, the iPad or the iPod. By adding data about other Apple products over time, we can visualize just how successful the iPhone has been compared to other products.</p><h4>4.4 Highlighting data with color</h4><p>Colors help direct viewers’ eyes to the most important parts of the figure. Colors tell your readers where to focus their attention. Grays help to tell viewers where to focus less of their attention, while other colors help to highlight the point your trying to make.</p><h4>4.5 Annotate your plot</h4><p>By highlighting parts of your plot with arrows or text on your plot, you can further draw viewers’ attention to certain part of the plot. These are often details that are unnecessary in exploratory plots, where the goal is just to better understand the data, but are very helpful in explanatory plots, when you’re trying to draw conclusions from the plot.</p><h4>4.6 What Does Your Final Chart Show?</h4><p>A plot title should first tell viewers what they would see in the plot. The second step is to show them with the plot. The third step is to make it extra clear to viewers what they should be seeing with descriptions, annotations, and legends. You explain to viewers what they should be seeing in the plot and the source of your data. Again, these are important pieces of creating a complete explanatory plot, but are not all necessary when making exploratory plots.</p><h4>4.7 Write precise descriptions</h4><p>Whether it’s a figure legend at the bottom of your plot, a subtitle explaining what data are plotted, or clear axes labels, text describing clearly what’s going on in your plot is important. Be sure that viewers are able to easily determine what each line or point on a plot represents.</p><h4>4.8 Add a source</h4><p>When finalizing an explanatory plot, be sure to source your data. It’s always best for readers to know where you obtained your data and what data are being used to create your plot. Transparency is important.</p><h3>5. ggplot2 Background</h3><p>The grammar of graphics implemented in ggplot2 is based on the idea that you can build <em>any</em> plot as long as you have a few pieces of information. To start building plots in ggplot2, we’ll need some data and we’ll need to know the type of plot we want to make. The type of plot you want to make in ggplot2 is referred to as a geom. This will get us started, but the idea behind ggplot2 is that every new concept we introduce will be layered on top of the information you’ve already learned. In this way, ggplot2 is <em>layered</em> — layers of information add on top of each other as you build your graph. In code written to generate a ggplot2 figure, you will see each line is separated by a plus sign (+). Think of each line as a different layer of the graph. We’re simply adding one layer on top of the previous layers to generate the graph. You’ll see exactly what we mean by this throughout each section in this lesson.</p><p>To get started, we’ll start with the two basics (data and a geom) and build additional layers from there.</p><p>As we get started plotting in ggplot2, plots will take the following general form:</p><pre>ggplot(data = DATASET) + <br>  geom_PLOT_TYPE(mapping = aes(VARIABLE(S)))</pre><p>When using ggplot2 to generate figures, you will always begin by calling the ggplot() function. You’ll then specify your dataset within the ggplot() function. Then, before making your plot you will also have to specify what <strong>geom</strong> type you’re interested in plotting. We’ll focus on a few basic geoms in the next section and give examples of each plot type (geom), but for now we’ll just work with a single geom: geom_point.</p><p>geom_point is most helpful for creating scatterplots. As a reminder from an earlier lesson, scatterplots are useful when you’re looking at the relationship between two numeric variables. Within geom you will specify the arguments needed to tell ggplot2 how you want your plot to look.</p><p>You will map your variables using the aesthetic argument <strong>aes</strong>. We’ll walk through examples below to make all of this clear. However, get comfortable with the overall look of the code now.</p><h4>5.1 Example Dataset: diamonds</h4><p>To build your first plot in ggplot2 we’ll make use of the fact that there are some datasets already available in R. One frequently-used dataset is known as diamonds. This dataset contains prices and other attributes of 53,940 diamonds, with each row containing information about a different diamond. If you look at the first few rows of data, you can get an idea of what data are included in this dataset.</p><pre>diamonds &lt;- as_tibble(diamonds)<br>diamonds<br>## # A tibble: 53,940 x 10<br>##    carat cut       color clarity depth table price     x     y     z<br>##    &lt;dbl&gt; &lt;ord&gt;     &lt;ord&gt; &lt;ord&gt;   &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;<br>##  1 0.23  Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43<br>##  2 0.21  Premium   E     SI1      59.8    61   326  3.89  3.84  2.31<br>##  3 0.23  Good      E     VS1      56.9    65   327  4.05  4.07  2.31<br>##  4 0.290 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63<br>##  5 0.31  Good      J     SI2      63.3    58   335  4.34  4.35  2.75<br>##  6 0.24  Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48<br>##  7 0.24  Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47<br>##  8 0.26  Very Good H     SI1      61.9    55   337  4.07  4.11  2.53<br>##  9 0.22  Fair      E     VS2      65.1    61   337  3.87  3.78  2.49<br>## 10 0.23  Very Good H     VS1      59.4    61   338  4     4.05  2.39<br>## # … with 53,930 more rows</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*7a0JoO15psGzDxgv" /></figure><p><em>Figure: First 12 rows of diamonds dataset</em></p><p>Here you see a lot of numbers and can get an idea of what data are available in this dataset. For example, in looking at the column names across the top, you can see that we have information about how many carats each diamond is (carat), some information on the quality of the diamond cut (cut), the color of the diamond from J (worst) to D (best) (color), along with a number of other pieces of information about each diamond.</p><p>We will use this dataset to better understand how to generate plots in R, using ggplot2.</p><h4>5.2 Scatterplots: geom_point()</h4><p>In ggplot2 we specify these by defining x and y <em>within</em> the aes() argument. The x argument defines which variable will be along the bottom of the plot. The y refers to which variable will be along the left side of the plot. If we wanted to understand the relationship between the number of carats in a diamond and that diamond’s price, we may do the following:</p><pre># generate scatterplot with geom_point()<br>ggplot(data = diamonds) + <br>  geom_point(mapping = aes(x = carat, y = price))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sHLy_8Xr-sWzBR6W" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*UKz9uznMRCO4ml7V" /></figure><p><em>Figure: diamonds scatterplot</em></p><p>In this plot, we see that, in general, the larger the diamond is (or the more carats it has), the more expensive the diamond is (price), which is probably what we would have expected. However, now, we have a plot that definitively supports this conclusion!</p><h4>5.3 Aesthetics</h4><p>What if we wanted to alter the size, color or shape of the points? Probably unsurprisingly, these can all be changed within the aesthetics argument. After all, something’s aesthetic refers to how something looks. Thus, if you want to change the look of your graph, you’ll want to play around with the plot’s aesthetics.</p><p>In fact, in the plots above you’ll notice that we specified what should be on the x and y axis within the aes() call. These are aesthetic mappings too! We were telling ggplot2 what to put on each axis, which will clearly affect how the plot looks, so it makes sense that these calls have to occur within aes(). Additionally now, we’ll focus on arguments within aes() that change how the points on the plot look.</p><h4>5.3.1 Point color</h4><p>In the scatterplot we just generated, we saw that there was a relationship between carat and price, such that the more carats a diamond has, generally, the higher the price. But, it’s not a perfectly linear trend. What we mean by that is that not all diamonds that were 2 carats were exactly the same price. And, not all 3 carat diamonds were exactly the same price. What if we were interested in finding out a little bit more about why this is the case?</p><p>Well, we could look at the clarity of the diamonds to see whether or not that affects the price of the diamonds? To add clarity to our plot, we could change the color of our points to differ based on clarity:</p><pre># adjusting color within aes<br>ggplot(data = diamonds) + <br>  geom_point(mapping = aes(x = carat, y = price, color = clarity))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*81AS20Z1yyeYLHiI" /></figure><p><em>Figure: changing point colors helps us better understand the data</em></p><p>Here, we see that not only are the points now colored by clarity, ggplot2 has also automatically added a legend for us with the various classes and their corresponding point color.</p><p>The Help pages of the diamonds dataset (accessed using ?diamonds) state that clarity is “a measurement of how clear the diamond is.” The documentation also tells us that I1 is the worst clarity and IF is the best (Full scale: I1, SI1, SI2, VS1, VS2, VVS1, VVS2, IF). This makes sense with what we see in the plot. Small (&lt;1 carat) diamonds that have the best clarity level (IF) are some of the most expensive diamonds. While, relatively large diamonds (diamonds between 2 and 3 carats) of the lowest clarity (I1) tend to cost less.</p><p>By coloring our points by a different variable in the dataset, we now understand our dataset better. This is one of the goals of data visualization! And, specifically, what we’re doing here in ggplot2 is known as <strong>mapping a variable to an aesthetic</strong>. We took another variable in the dataset, mapped it to a color, and then put those colors on the points in the plot. Well, we only told ggplot2 what variable to map. It took care of the rest!</p><p>Of course, we can also <em>manually</em> specify the colors of the points on our graph; however, manually specifying the colors of points happens <em>outside</em> of the aes() call. This is because ggplot2 does not have to go through the mapping the variable to an aesthetic process. In the code here, ggplot2 doesn’t have to go through the trouble of figuring out which level of the variable is going to be which color on the plot (the mapping to the aesthetic part of the process). Instead, it just colors every point red. Thus, <strong>manually specifying the color of your points happens <em>outside</em> of aes()</strong>:</p><pre># manually control color point outside aes<br>ggplot(data = diamonds) + <br>  geom_point(mapping = aes(x = carat, y = price), color = &quot;red&quot;) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*78Qi4uyJJ0egjHSs" /></figure><p><em>Figure: manually specifying point color occurs outside of</em> aes()</p><h4>5.3.2 Point size</h4><p>As above, we can change the point size by mapping another variable to the size argument within aes:</p><pre># adjust point size within aes<br>ggplot(data = diamonds) + <br>  geom_point(mapping = aes(x = carat, y = price, size = clarity))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-1aY7wz6svweWUh3" /></figure><p><em>Figure: mapping to size changes point size on plot</em></p><p>As above, ggplot2 handles the mapping process. All you have to do is specify what variable you want mapped (clarity) and how you want ggplot2 to handle the mapping (change the point size). With this code, you do get a warning when you run it in R that using a “discrete variable is not advised.” This is because mapping to size is usually done for numeric variables, rather than categorical variables like clarity.</p><p>This makes sense here too. The relationship between clarity, carat, and price was easier to visualize when clarity was mapped to color than here where it is mapped to size.</p><p>Like the above example with color, the size of <em>every</em> point can be changed by calling size outside of aes:</p><pre># global control of point size<br>ggplot(data = diamonds) + <br>  geom_point(mapping = aes(x = carat, y = price), size = 4.5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vaDyZkP-CjQaFH5G" /></figure><p><em>Figure: manually specifying point size of all points occurs outside of </em>aes()</p><p>Here, we have manually increased the size of <em>all</em> the points on the plot.</p><h4>5.3.3 Point Shape</h4><p>You can also change the shape of the points (shape). We’ve used solid, filled circles thus far (the default in geom_point), but we could specify a different shape for each clarity.</p><pre># map clarity to point shape within aes <br>ggplot(data = diamonds) + <br>  geom_point(mapping = aes(x = carat, y = price, shape = clarity))<br>## Warning: Using shapes for an ordinal variable is not advised<br>## Warning: The shape palette can deal with a maximum of 6 discrete values because<br>## more than 6 becomes difficult to discriminate; you have 8. Consider<br>## specifying shapes manually if you must have them.<br>## Warning: Removed 5445 rows containing missing values (geom_point).</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L7eA3bEHraexZr22" /></figure><p><em>Figure: mapping clarity to shape</em></p><p>Here, while the mapping occurs correctly within ggplot2, we do get a warning message that discriminating more than six different shapes is difficult for the human eye. Thus, ggplot2 won’t allow more than six different shapes on a plot. This suggests that while you <em>can</em> do something, it’s not always the <em>best</em> to do that thing. Here, with more than six levels of clarity, it’s best to stick to mapping this variable to color as we did initially.</p><p>To manually specify a shape for all the points on your plot, you would specify it outside of aes using one of the twenty-five different shape options available:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*5Nl6E9VkNNx_HqBY" /></figure><p><em>Figure: options for points in ggplot2’s </em>shape</p><p>For example, to plot all of the points on the plot as filled diamonds (it is a dataset about diamonds after all…), you would specify shape ‘18’:</p><pre># global control of point shape outside aes<br>ggplot(data = diamonds) + <br>  geom_point(mapping = aes(x = carat, y = price), shape = 18)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TfcXJHcmQ9Pcwuff" /></figure><p><em>Figure: specifying filled diamonds as shape for all points manually</em></p><h4>5.4 Facets</h4><p>In addition to mapping variables to different aesthetics, you can also opt to use facets to help make sense of your data visually. Rather than plotting all the data on a single plot and visually altering the point size or color of a third variable in a scatterplot, you could break each level of that third variable out into a separate subplot. To do this, you would use faceting. Faceting is particularly helpful for looking at categorical variables.</p><p>To use faceting, you would add an additional layer (+) to your code and use the facet_wrap() function. Within facet wrap, you specify the variable by which you want your subplots to be made:</p><pre>ggplot(data = diamonds) + <br>  geom_point(mapping = aes(x = carat, y = price)) + <br>  # facet by clarity<br>  facet_wrap(~clarity, nrow = 2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EHwi-ByProsYVMtC" /></figure><p>Here, read the tilde as the word “by”. Specifically here, we want a scatterplot of the relationship between carat and price and we want it faceted (broken down) <strong>by (~)</strong> clarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*TMu62xBe1npkFxUt" /></figure><p><em>Figure: facet_wrap breaks plots down into subplots</em></p><p>Now, we have eight different plots, one for each level of clarity, where we can see the relationship between diamond carats and price.</p><p>You’ll note here we’ve opted to specify that we want 2 rows of subplots (nrow = 2). You can play around with the number of rows you want in your output to customize how your output plot appears.</p><h4>5.5 Geoms</h4><p>Thus far in this lesson we’ve only looked at scatterplots, which means we’ve only called geom_point. However, there are <em>many</em> additional geoms that we could call to generate different plots. Simply, a <em>geom</em> is just a shape we use to represent the data. In the case of scatterplots, they don’t <em>really</em> use a geom since each actual point is plotted individually. Other plots, such as the boxplots, barplots, and histograms we described in previous lessons help to summarize or represent the data in a meaningful way, without plotting each individual point. The shapes used in these different types of plots to represent what’s going on in the data is that plot’s geom.</p><p>To see exactly what we mean by geoms being “shapes that represent the data”, let’s keep using the diamonds dataset, but instead of looking at the relationship between two numeric variables in a scatterplot, let’s take a step back and take a look at a single numeric variable using a histogram.</p><h4>5.5.1 Histograms: geom_histogram</h4><p>To review, histograms allow you to quickly visualize the range of values your variable takes and the shape of your data. (Are all the numbers clustered around center? Or, are they all at the extremes of the range? Somewhere in between? The answers to these questions describe the “shape” of the values of your variable.)</p><p>For example, if we wanted to see what the distribution of carats was for these data, we could to the following.</p><pre># change geom_ to generate histogram<br>ggplot(data = diamonds) + <br>  geom_histogram(mapping =  aes(carat))<br>## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n2KLOmTPnAgtKPeG" /></figure><p><em>Figure: histogram of carat shows range and shape</em></p><p>The code follows what we’ve seen so far in this lesson; however, we’ve now called geom_histogram to specify that we want to plot a histogram rather than a scatterplot.</p><p>Here, the rectangular boxes on the plot are geoms (shapes) that represent the number of diamonds that fall into each bin on the plot. Rather than plotting each individual point, histograms use rectangular boxes to summarize the data. This summarization helps us quickly understand what’s going on in our dataset.</p><p>Specifically here, we can quickly see that most of the diamonds in the dataset are less than 1 carat. This is not necessarily something we could be sure of from the scatterplots generated previously in this lesson (since some points could have been plotted directly on top of one another). Thus, it’s often helpful to visualize your data in a number of ways when you first get a dataset to ensure that you understand the variables and relationships between variables in your dataset!</p><h4>5.5.2 Barplots: geom_bar</h4><p>Barplots show the relationship between a set of numbers and a categorical variable. In the diamonds dataset, we may be interested in knowing how many diamonds there are of each cut of diamonds. There are five categories for cut of diamond. If we make a barplot for this variable, we can see the number of diamonds in each category.</p><pre># geom_bar for bar plots<br>ggplot(data = diamonds) + <br>  geom_bar(mapping = aes(cut))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HRp-IRw4jCDQrM2m" /></figure><p>Again, the changes to the code are minimal. We are now interested in plotting the categorical variable cut and state that we want a bar plot, by including geom_bar().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*iInohr5uGbOnuqtC" /></figure><p><em>Figure: diamonds barplot</em></p><p>Here, we again use rectangular shapes to represent the data, but we’re not showing the distribution of a single variable (as we were with geom_histogram). Rather, we’re using rectangles to show the count (number) of diamonds within each category within cut. Thus, we need a different geom: geom_bar!</p><h4>5.5.3 Boxplots: geom_boxplot</h4><p>Boxplots provide a summary of a numerical variable across categories. For example, if you were interested to see how the price of a diamond (a numerical variable) changed across different diamond color categories (categorical variable), you may want to use a boxplot. To do so, you would specify that using geom_boxplot:</p><pre># geom_boxplot for boxplots<br>ggplot(data = diamonds) + <br>  geom_boxplot(mapping = aes(x = color, y = price))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RVKfMh_gNDglhg2G" /></figure><p>In the code, we see that again, we only have to change what variables we want to be included in the plot and the type of plot (or geom). We want to use `geom_boxplot()` to get a basic boxplot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*DBe9kXU-gUI_xGNl" /></figure><p><em>Figure: diamonds boxplot</em></p><p>In the figure itself we see that the median price (the black horizontal bar in the middle of each box represents the median for each category) increases as the diamond color increases from the worst category (J) to the best (D).</p><p>Now, if you wanted to change the color of this boxplot, it would just take a small addition to the code for the plot you just generated.</p><pre># fill globally changes bar color outside aes<br>ggplot(data = diamonds) + <br>  geom_boxplot(mapping = aes(x = color, y = price), <br>               fill = &quot;red&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vEhtHP1HMBA5yNLk" /></figure><p>Figure: diamonds boxplot with red fill</p><p>Here, by specifying the color “red” in the fill argument, you’re able to change the plot’s appearance. In the next lesson, we’ll go deeper into the many ways in which a plot can be customized within ggplot2!</p><h4>5.5.4 Other plots</h4><p>While we’ve reviewed basic code to make a few common types of plots, there are a number of other plot types that can be made in ggplot2. These are listed in the <a href="http://ggplot2.tidyverse.org/reference/">online reference material for ggplot2</a> or can be accessed through RStudio directly. To do so, you would type ?geom_ into the Console in RStudio. A list of geoms will appear. You can hover your cursor over any one of these to get a short description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*gyXrWdQKwUwzq9In" /></figure><p><em>Figure: ?geom in Console</em></p><p>Or, you can select a geom from this list and click enter. After selecting a geom, such as geom_abline and hitting ‘Enter,’ the help page for that geom will pop up in the ‘Help’ tab at bottom right. Here, you can find more detailed information about the selected geom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*riQd_c4iFKxFqez4" /></figure><p><em>Figure: geom_abline help page</em></p><h4>5.6 EDA Plots</h4><p>As mentioned previously, an important step after you’ve read your data into R and wrangled it into a tidy format is to carry out <strong>Exploratory Data Analysis (EDA)</strong>. EDA is the process of understanding the data in your dataset fully. To understand your dataset fully, you need a full understanding of the variables stored in your dataset, what information you have and what information you don’t have (missingness!). To gain this understanding, we’ve discussed using packages like skimr to get a quick idea of what information is stored in your dataset. However, generating plots is another critical step in this process. We encourage you to use ggplot2 to understand the distribution of each single variable as well as the relationship between each variable in your dataset.</p><p>In this process, using ggplot2 defaults is totally fine. These plots do not have to be the most effective visualizations for communication, so you don’t want to spend a ton of time making them visually perfect. Only spend as much time on these as you need to understand your data!</p><h3>6. ggplot Customization</h3><h4>6.1 Colors</h4><p>To get started, we’ll learn how to control color across plots in ggplot2. Previously, we discussed using color within aes() on a scatterplot to automatically color points by the clarity of the diamond when looking at the relationship between price and carat.</p><pre>ggplot(diamonds) + <br>  geom_point(mapping = aes(x = carat, y = price, color = clarity))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8DWXqTZ8ayQ7YU5R" /></figure><p>However, what if we wanted to carry this concept over to a bar plot and look at how many diamonds we have of each clarity group?</p><pre># generate bar plot<br>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IAfPmbrnBFvWrz5J" /></figure><p><em>Figure: diamonds broken down by clarity</em></p><p>As a general note, we’ve stopped including data = and mapping = here within our code. We included it so far to be explicit; however, in code you see in the world, the names of the arguments will typically be excluded and we want you to be familiar with code that appears as you see above.</p><p>OK, well that’s a start since we see the breakdown, but all the bars are the same color. What if we adjusted color within aes()?</p><pre># color changes outline of bar<br>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity, color = clarity))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*622z8Wd_-aDWd11C" /></figure><p><em>Figure: color does add color but around the bars</em></p><p>As expected, color added a legend for each level of clarity; however, it colored the lines around the bars on the plot, rather than the bars themselves. In order to color the bars themselves, you want to specify the more helpful argument fill:</p><pre># use fill to color bars<br>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity, fill = clarity))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZnseTrLkmLt9-Xoe" /></figure><p>Figure: fill automatically colors the bars</p><p>Great! We now have a plot with bars of different colors, which was our first goal! However, adding colors here, while maybe making the plot prettier doesn’t actually give us any more information. We can see the same pattern of which clarity is most frequent among the diamonds in our dataset like we could see in the first plot we made.</p><p>Color is particularly helpful here, however, if we wanted to map a <em>different</em> variable onto each bar. For example, what if we wanted to see the breakdown of diamond “cut” within each “clarity” bar?</p><pre># fill by separate variable (cut) = stacked bar chart<br>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity, fill = cut))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E5GPG6kHZbsfLEPz" /></figure><p><em>Figure: mapping a different variable to fill provides new information</em></p><p>Now we’re getting some new information! We can see that each level in clarity appears to have diamonds of all levels of cut. Color here has really helped us understand more about the data.</p><p>But what if we were going to present these data? While there is no comparison between red and green (which is good!), there is a fair amount of yellow in this plot. Some projectors don’t handle projecting yellow well, and it will show up too light on the screen. To avoid this, let’s manually change the colors in this bar chart! To do so we’ll add an additional layer to the plot using scale_fill_manual.</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity, fill = cut)) +<br>  # manually control colors used<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bgYJvKqSYdmQXtfW" /></figure><p>Figure: manually setting colors using scale_fill_manual</p><p>Here, we’ve specified five different colors within the values argument of scale_fill_manual(), one for each cut of diamond. The names of these colors can be specified using the names explained on the third page of the cheatsheet <a href="https://www.nceas.ucsb.edu/~frazier/RSpatialGuides/colorPaletteCheatsheet.pdf">here</a>. (Note: There are other ways to specify colors within R. Explore the details in that cheatsheet to better understand the various ways!)</p><p>Additionally, it’s important to note that here we’ve used scale_fill_manual() to adjust the color of what was mapped using fill = cut. If we had colored our chart using color within aes(), there is a different function called scale_color_manual. This makes good sense! You use scale_fill_manual() with fill and scale_color_manual() with color. Keep that in mind as you adjust colors in the future!</p><p>Now that we have some sense of which clarity is most common in our diamonds dataset and now that we are able to successfully specify the colors we want manually in order to make this plot useful for presentation, what if we wanted to compare the proportion of each cut across the different clarities? Currently, that’s difficult because there is a different number within each clarity. In order to compare the proportion of each cut we have to use <strong>position adjustment</strong>.</p><p>What we’ve just generated is a <strong>stacked bar chart</strong>. It’s a pretty good name for this type of chart as the bars for cut are all stacked on top of one another. If you don’t want a stacked bar chart you could use one of the other position options: identity, fill, or dodge.</p><p>Returning to our question about proportion of each cut within each clarity group, we’ll want to use position = “fill” within geom_bar(). Building off of what we’ve already done:</p><pre>ggplot(diamonds) + <br>  # fill scales to 100%<br>  geom_bar(aes(x = clarity, fill = cut), position = &quot;fill&quot;) +<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pDcUnQ_TT4XreDJA" /></figure><p>Figure: position = “fill” allows for comparison of proportion across groups</p><p>Here, we’ve specified how we want to adjust the position of the bars in the plot. Each bar is now of equal height and we can compare each colored bar across the different clarities. As expected, we see that among the best clarity group (IF), we see more diamonds of the best cut (“Ideal”)!</p><p>Briefly, we’ll take a quick detour to look at position = “dodge”. This position adjustment places each object <em>next to one another</em>. This will not allow for easy comparison across groups, as we just saw with the last group but will allow values within each clarity group to be visualized.</p><pre>ggplot(diamonds) + <br>  # dodge rather than stack produces grouped bar plot<br>  geom_bar(aes(x = clarity, fill = cut), position = &quot;dodge&quot;) +<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*JnsPuDOEFlPtP5O8" /></figure><p>Figure: position = “dodge” helps compare values within each group</p><p>Unlike in the first plot where we specified fill = cut, we can actually see the relationship between each cut within the lowest clarity group (I1). Before, when the values were stacked on top of one another, we were not able to visually see that there were more “Fair” and “Premium” cut diamonds in this group than the other cuts. Now, with position = “dodge”, this information is visually apparent.</p><p>Note: position = “identity” is not very useful for bars, as it <em>places each object exactly where it falls within the graph</em>. For bar charts, this will lead to <em>overlapping bars</em>, which is not visually helpful. However, for scatterplots (and other 2-Dimensional charts), this is the default and is exactly what you want.</p><h4>6.2 Labels</h4><p>Text on plots is incredibly helpful. A good title tells viewers what they should be getting out of the plot. Axis labels are incredibly important to inform viewers of what’s being plotted. Annotations on plots help guide viewers to important points in the plot. We’ll discuss how to control all of these now!</p><h4>6.2.1 Titles</h4><p>Now that we have an understanding of how to manually adjust color, let’s improve the clarity of our plots by including helpful labels by adding an additional labs() layer. We’ll return to the plot where we were comparing proportions of diamond cut across diamond clarity groups.</p><p>You can include a title, subtitle, and/or caption within the labs() function. Each argument, as per usual, will be specified by a comma.</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity, fill = cut), position = &quot;fill&quot;) +<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;)) +<br>  # add titles<br>  labs(title = &quot;Clearer diamonds tend to be of higher quality cut&quot;,<br>       subtitle = &quot;The majority of IF diamonds are an \&quot;Ideal\&quot; cut&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nSurjyJVYdSWwQJS" /></figure><p>Figure: labs() adds helpful tittles, subtitles, and captions</p><h4>6.2.2 Axis labels</h4><p>You may have noticed that our y-axis label says “count”, but it’s not actually a count anymore. In reality, it’s a proportion. Having appropriately labeled axes is <em>so important</em>. Otherwise, viewers won’t know what’s being plotted. So, we should really fix that now using the ylab() function. Note: we won’t be changing the x-axis label, but if you were interested in doing so, you would use xlab(“label”).</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity, fill = cut), position = &quot;fill&quot;) +<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;)) +<br>  labs(title = &quot;Clearer diamonds tend to be of higher quality cut&quot;,<br>       subtitle = &quot;The majority of IF diamonds are an \&quot;Ideal\&quot; cut&quot;) +<br>  # add y axis label explicitly<br>  ylab(&quot;proportion&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_YlPEzKH3TIHCr-1" /></figure><p>Figure: Accurate axis labels are incredibly important</p><p>Note that the x- and y- axis labels can <em>also</em> be changed within labs(), using the argument (x = and y = respectively).</p><h3>6.3 Themes</h3><p>To change the overall aesthetic of your graph, there are 8 themes built into ggplot2 that can be added as an additional layer in your graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*1YfTNevlWTgUikSc" /></figure><p><em>Figure: themes</em></p><p>For example, if we wanted remove the gridlines and grey background from the chart, we would use theme_classic(). Building on what we’ve already generated:</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity, fill = cut), position = &quot;fill&quot;) +<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;)) +<br>  labs(title = &quot;Clearer diamonds tend to be of higher quality cut&quot;,<br>       subtitle = &quot;The majority of IF diamonds are an \&quot;Ideal\&quot; cut&quot;) +<br>  ylab(&quot;proportion&quot;) +<br>  # change plot theme<br>  theme_classic()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PsRrIo_pZE98kXp2" /></figure><p>Figure: theme_classic changes aesthetic of our plot</p><p>We now have a pretty good looking plot! However, a few additional changes would make this plot <em>even better</em> for communication.</p><p>Note: Additional themes are available from the <a href="https://yutannihilation.github.io/allYourFigureAreBelongToUs/ggthemes/">ggthemes</a> package . Users can also generate their own themes.</p><h4>6.4 Custom Theme</h4><p>In addition to using available themes, we can also adjust parts of the theme of our graph using an additional theme() layer. There are <strong>a lot</strong> of options within theme. To see them all, look at the help documentation within RStudio Cloud using: ?theme. We’ll simply go over the syntax for using a few of them here to get you comfortable with adjusting your theme. Later on, you can play around with all the options on your own to become an expert!</p><h4>6.4.1 Altering text size</h4><p>For example, if we want to increase text size to make our plots more easily to view when presenting, we could do that within theme. Notice here that we’re increasing the text size of the title, axis.text, axis.title, and legend.text all within theme()! The syntax here is important. Within each of the elements of the theme you want to alter, you have to specify what it is you want to change. Here, for all three, we want to alter the text, so we specify element_text(). Within that, we specify that it’s size that we want to adjust.</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity, fill = cut), position = &quot;fill&quot;) +<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;)) +<br>  labs(title = &quot;Clearer diamonds tend to be of higher quality cut&quot;,<br>       subtitle = &quot;The majority of IF diamonds are an \&quot;Ideal\&quot; cut&quot;) +<br>  ylab(&quot;proportion&quot;) +<br>  theme_classic() +<br>  # control theme<br>  theme(title = element_text(size = 16), <br>        axis.text = element_text(size =14),<br>        axis.title = element_text(size = 16),<br>        legend.text = element_text(size = 14))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iZBI_IaIZzrVmb1Y" /></figure><p>Figure: theme() allows us to adjust font size</p><h4>6.4.2 Additional text alterations</h4><p>Changing the size of text on your plot is not the only thing you can control within theme(). You can make text <strong>bold </strong>and change its color within theme().<strong> </strong>Note here that multiple changes can be made to a single element. We can change size and make the text bold. All we do is separate each argument with a comma, per usual.</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity, fill = cut), position = &quot;fill&quot;) +<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;)) +<br>  labs(title = &quot;Clearer diamonds tend to be of higher quality cut&quot;,<br>       subtitle = &quot;The majority of IF diamonds are an \&quot;Ideal\&quot; cut&quot;) +<br>  ylab(&quot;proportion&quot;) +<br>  theme_classic() +<br>  theme(title = element_text(size = 16), <br>        axis.text = element_text(size = 14),<br>        axis.title = element_text(size = 16, face = &quot;bold&quot;),<br>        legend.text = element_text(size = 14),<br>        # additional control<br>        plot.subtitle = element_text(color = &quot;gray30&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GypfZkU8IWBtJ-hh" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*1x51eMGSHDK8TKq8" /></figure><p>Figure: theme() allows us to tweak many parts of our plot</p><p>Any alterations to plot spacing/background, title, axis, and legend will all be made within theme()</p><h3>6.5 Legends</h3><p>At this point, all the text on the plot is pretty visible! However, there’s one thing that’s still not quite clear to viewers. In daily life, people refer to the “cut” of a diamond by terms like “round cut” or “princess cut” to describe the <em>shape</em> of the diamond. That’s not what we’re talking about here when we’re discussing “cut”. In these data, “cut” refers to the quality of the diamond, not the shape. Let’s be sure that’s clear as well! We can change the name of the legend by using an additional layer and the guides() and guide_legend() functions of the ggplot2 package!</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity, fill = cut), position = &quot;fill&quot;) +<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;)) +<br>  labs(title = &quot;Clearer diamonds tend to be of higher quality cut&quot;,<br>       subtitle = &quot;The majority of IF diamonds are an \&quot;Ideal\&quot; cut&quot;) +<br>  ylab(&quot;proportion&quot;) +<br>  theme_classic() +<br>  theme(title = element_text(size = 16), <br>        axis.text = element_text(size = 14),<br>        axis.title = element_text(size = 16, face = &quot;bold&quot;),<br>        legend.text = element_text(size = 14),<br>        plot.subtitle = element_text(color = &quot;gray30&quot;)) +<br>  # control legend<br>  guides(fill = guide_legend(&quot;cut quality&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4iMKZm1vYHwIrSL4" /></figure><p>Figure: guides() allows us to change the legend title</p><p>This guides() function, as well as the guides_* functions also allow us to modify legends even further.</p><p>This is especially useful if you have many colors in your legend and you want to control how the legend is displayed in terms of the number of columns and rows using ncol and nrow respectively.</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity, fill = cut), position = &quot;fill&quot;) +<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;)) +<br>  labs(title = &quot;Clearer diamonds tend to be of higher quality cut&quot;,<br>       subtitle = &quot;The majority of IF diamonds are an \&quot;Ideal\&quot; cut&quot;) +<br>  ylab(&quot;proportion&quot;) +<br>  theme_classic() +<br>  theme(title = element_text(size = 16), <br>        axis.text = element_text(size = 14),<br>        axis.title = element_text(size = 16, face = &quot;bold&quot;),<br>        legend.text = element_text(size = 14),<br>        plot.subtitle = element_text(color = &quot;gray30&quot;)) +<br>  # control legend<br>  guides(fill = guide_legend(&quot;Cut Quality&quot;, <br>                              ncol = 2))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WjKmHs_MoxFeu4FZ" /></figure><p>Or, we can modify the font of the legend title using title.theme().</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity, fill = cut), position = &quot;fill&quot;) +<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;)) +<br>  labs(title = &quot;Clearer diamonds tend to be of higher quality cut&quot;,<br>       subtitle = &quot;The majority of IF diamonds are an \&quot;Ideal\&quot; cut&quot;) +<br>  ylab(&quot;proportion&quot;) +<br>  theme_classic() +<br>  theme(title = element_text(size = 16), <br>        axis.text = element_text(size = 14),<br>        axis.title = element_text(size = 16, face = &quot;bold&quot;),<br>        legend.text = element_text(size = 14),<br>        plot.subtitle = element_text(color = &quot;gray30&quot;)) +<br>  # control legend<br>  guides(fill = guide_legend(&quot;Cut Quality&quot;, <br>                             title.theme = element_text(face = &quot;bold&quot;)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5t5nz0c9SbVS1LgS" /></figure><p>Alternatively, we can do this modification, as well as other legend modifications, like adding a rectangle around the legend, using the theme() function.</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity, fill = cut), position = &quot;fill&quot;) +<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;)) +<br>  labs(title = &quot;Clearer diamonds tend to be of higher quality cut&quot;,<br>       subtitle = &quot;The majority of IF diamonds are an \&quot;Ideal\&quot; cut&quot;) +<br>  ylab(&quot;proportion&quot;) +<br># changing the legend title:<br>guides(fill = guide_legend(&quot;Cut Quality&quot;)) +<br>  theme_classic() +<br>  theme(title = element_text(size = 16), <br>        axis.text = element_text(size = 14),<br>        axis.title = element_text(size = 16, face = &quot;bold&quot;),<br>        legend.text = element_text(size = 14),<br>        plot.subtitle = element_text(color = &quot;gray30&quot;),<br># changing the legend style:<br>        legend.title = element_text(face = &quot;bold&quot;),<br>        legend.background = element_rect(color = &quot;black&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DliqgfAyvLoFdbKj" /></figure><p>At this point, we have an informative title, clear colors, a well-labeled legend, and text that is large enough throughout the graph. This is certainly a graph that could be used in a presentation. We’ve taken it from a graph that is useful to just ourselves (exploratory) and made it into a plot that can communicate our findings well to others (explanatory)!</p><p>We have touched on a number of alterations you can make by adding additional layers to a ggplot. In the rest of this lesson we’ll touch on a few more changes you can make within ggplot2.</p><h4>6.6 Scales</h4><p>There may be times when you want a different number of values to be displayed on an axis. The scale of your plot for <strong>continuous variables</strong> (i.e. numeric variables) can be controlled using scale_x_continuous or scale_y_continuous. Here, we want to increase the number of labels displayed on the y-axis, so we’ll use scale_y_continuous:</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity)) +<br>  # control scale for continuous variable<br>  scale_y_continuous(breaks = seq(0, 17000, by = 1000))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qR7-4d1wiaqsdyZY" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*2bK0OQOuUhrZvskb" /></figure><p><em>Figure: Continuous scales can be altered</em></p><p>There is very handy argument called trans for the scale_y_continuous or the scale_x_continuous functions to change the scale of the axes. For example it can be very useful to show the logarithmic version of the scale if you have very high values with large differences.</p><p>According to the documentation for the trans argument: &gt; Built-in transformations include “asn”, “atanh”, “boxcox”, “date”, “exp”, “hms”, “identity”, “log”, “log10”, “log1p”, “log2”, “logit”, “modulus”, “probability”, “probit”, “pseudo_log”, “reciprocal”, “reverse”, “sqrt” and “time”.</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity)) +<br>  # control scale for continuous variable<br>  scale_y_continuous(trans = &quot;log10&quot;) +<br>    labs(y = &quot;Count (log10 scale)&quot;,<br>         x = &quot;Clarity&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SX_m8JTyZjY9bBU0" /></figure><p>Notice that the values are not changed, just the way they are plotted. Now the y-axis increases by a factor of 10 for each break.</p><p>We will create a plot of the price of the diamonds to demonstrate the utility of creating a plot with a log10 scaled y-axis.</p><pre>ggplot(diamonds) + <br>  geom_boxplot(aes(y = price, x = clarity))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HbSJtmKVDm08R8Kk" /></figure><pre>ggplot(diamonds) + <br>  geom_boxplot(aes(y = price, x = clarity)) + <br>  scale_y_continuous(trans = &quot;log10&quot;) + <br>  labs(y = &quot;Price (log10 scale)&quot;,<br>       x = &quot;Diamond Clarity&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d7eb-0m5KGlsHzhe" /></figure><p>In the first plot, it is difficult to tell what values the boxplots correspond to and it is difficult to compare the boxplots (particularly for the last three clarity categories), however this is greatly improved in the second plot.</p><p>We can also use another argument of the scale_y_continuous() function to add specific labels to our plot. For example, it would be nice to add dollar signs to the y-axis. We can do so using the labels argument. A variety of label_* functions within the scales package can be used to modify axis labels. See <a href="https://scales.r-lib.org/reference/index.html">here</a> to take a look at the many options.</p><pre>ggplot(diamonds) + <br>  geom_boxplot(aes(y = price, x = clarity)) + <br>  scale_y_continuous(trans = &quot;log10&quot;, <br>                    labels = scales::label_dollar()) +<br>  labs(y = &quot;Price (log10 scale)&quot;,<br>       x = &quot;Diamond Clarity&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wnD84jvAp5Yf4A4q" /></figure><p>Now we can more easily determine that the SI2 diamonds are the most expensive.</p><p>Another way to modify <strong>discrete variables</strong> (aka factors or categorical variables where there is a limited number of levels), is to use scale_x_discrete or scale_y_discrete. In this case we will just pick a few of the clarity categories to plot and we will specify the order.</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity)) +<br>  # control scale for discrete variable<br>  scale_x_discrete(limit = c(&quot;SI2&quot;, &quot;SI1&quot;, &quot;I1&quot;)) +<br>  scale_y_continuous(breaks = seq(0, 17000, by = 1000))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*TMczMI9AHfc1k-n3" /></figure><p><em>Figure: Discrete scales can be altered</em></p><h4>6.7 Coordinate Adjustment</h4><p>There are times when you’ll want to flip your axis. This can be accomplished using coord_flip(). Adding an additional layer to the plot we just generated switches our x- and y-axes, allowing for horizontal bar charts, rather than the default vertical bar charts:</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity)) +<br>  scale_y_continuous(breaks = seq(0, 17000, by = 1000)) +<br>  scale_x_discrete(limit = c(&quot;SI2&quot;, &quot;SI1&quot;, &quot;I1&quot;)) +<br>  # flip coordinates<br>  coord_flip() +<br>  labs(title = &quot;Clearer diamonds tend to be of higher quality cut&quot;,<br>       subtitle = &quot;The majority of IF diamonds are an \&quot;Ideal\&quot; cut&quot;) +<br>  ylab(&quot;proportion&quot;) +<br>  theme_classic() +<br>  theme(title = element_text(size = 18), <br>        axis.text = element_text(size = 14),<br>        axis.title = element_text(size = 16, face = &quot;bold&quot;),<br>        legend.text = element_text(size = 14),<br>        plot.subtitle = element_text(color = &quot;gray30&quot;)) +<br>  guides(fill = guide_legend(&quot;cut quality&quot;)) <br>## Warning: Removed 30940 rows containing non-finite values (stat_count).</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UzNqs1PIZZSowL0u" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*p_4cQ-Dl-jI-AcNO" /></figure><p>Figure: Axes can be flipped using coord_flip</p><p>It’s important to remember that all the additional alterations we already discussed can still be applied to this graph, due to the fact that ggplot2 uses layering!</p><pre>p &lt;- ggplot(diamonds) + <br>  geom_bar(mapping = aes(x = clarity)) +<br>  scale_y_continuous(breaks = seq(0, 17000, by = 1000)) +<br>  scale_x_discrete(limit = c(&quot;SI2&quot;, &quot;SI1&quot;, &quot;I1&quot;)) +<br>  coord_flip() +<br>  labs(title = &quot;Number of diamonds by diamond clarity&quot;,<br>       subtitle = &quot;Subset of all diamonds, looking three levels of clarity&quot;) +<br>  theme_classic() +<br>  theme(title = element_text(size = 18), <br>        axis.text = element_text(size = 14),<br>        axis.title = element_text(size = 16, face = &quot;bold&quot;),<br>        legend.text = element_text(size = 14),<br>        plot.subtitle = element_text(color = &quot;gray30&quot;) ) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*O9xXJXP5QYk98zj5" /></figure><p><em>Figures: Additional layers will help customize this plot</em></p><h4>6.8 Annotation</h4><p>Finally, there will be times when you’ll want to add text to a plot or to annotate points on your plot. We’ll discuss briefly how to accomplish that here!</p><p>To add text to your plot, we can use the function annotate. This requires us to specify that we want to annotate here with “text” (rather than say a shape, like a rectangle — “rect” — which you can also do!). Additionally, we have to specify what we’d like that text to say (using the label argument), where on the plot we’d like that text to show up (using x and y for coordinates), how we’d like the text aligned (using hjust for horizontal alignment where the options are “left”, “center”, or “right” and vjust for vertical alignment where the arguments are “top”, “center”, or “bottom”), and how big we’d like that text to be (using size):</p><pre>ggplot(diamonds) + <br>  geom_bar(aes(x = clarity)) +<br>  scale_y_continuous(breaks = seq(0, 17000, by = 1000)) +<br>  scale_x_discrete(limit = c(&quot;SI2&quot;, &quot;SI1&quot;, &quot;I1&quot;)) +<br>  coord_flip() +<br>  labs(title = &quot;Number of diamonds by diamond clarity&quot;,<br>       subtitle = &quot;Subset of all diamonds, looking three levels of clarity&quot;) +<br>  theme_classic() +<br>  theme(title = element_text(size = 18), <br>        axis.text = element_text(size = 14),<br>        axis.title = element_text(size = 16, face = &quot;bold&quot;),<br>        legend.text = element_text(size = 14),<br>        plot.subtitle = element_text(color = &quot;gray30&quot;)) +<br>  # add annotation<br>  annotate(&quot;text&quot;, label = &quot;SI1 diamonds are among \n the most frequent clarity diamond&quot;, <br>           y = 12800, x = 2.9, <br>           vjust = &quot;top&quot;, hjust = &quot;right&quot;, <br>           size = 6)<br>## Warning: Removed 30940 rows containing non-finite values (stat_count).</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*erG7OSnM7UA1Zkft" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*7J50k-TsyVnbBx8t" /></figure><p>Figure: annotate helps add text to our plot</p><p>Note: we could have accomplished this by adding an additional geom: geom_text. However, this requires creating a new dataframe, as explained <a href="http://r4ds.had.co.nz/graphics-for-communication.html#annotations">here</a>. This can also be used to <strong>label the points on your plot</strong>. Keep this reference in mind in case you have to do that in the future.6.10 Vertical and Horizontal Lines</p><h4>6.9 Vertical and Horizontal Lines</h4><p>Sometimes it is very useful to add a line to our plot to indicate an important threshold. We can do so by using the geom_hline() function for a horizontal line and geom_vline() for a vertical line.</p><p>In each case, the functions require that a y or x intercept be specified respectively.</p><p>For example, it might be useful to add a horizontal line to indicate 50% of the total counts for each of the clarity categories. We will also use the scale_y_continuous() function to change the y-axis to show percentages.</p><pre>ggplot(diamonds) + <br>  # fill scales to 100%<br>  geom_bar(aes(x = clarity, fill = cut), position = &quot;fill&quot;) +<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;)) +<br>  scale_y_continuous(labels = scales::percent) +<br>  labs(y = &quot;Percent of diamonds&quot;) +<br>  geom_hline(yintercept = 0.5, color = &quot;red&quot;, size = 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l8Dh9C3Xp9N970q7" /></figure><p>Now it’s easier to tell that slightly over half of the VVS2 diamonds have an Ideal cut. This would be much more difficult to see without the horizontal line.</p><p>To add a vertical line we would instead use the geom_vline() function and we would specify an x-axis intercept. Since this plot has a discrete x-axis, numeric values specify a categorical value based on the order, thus a value of 4 would create a line down the center of the VS2 bar. However, if we used 5.5 we could add a line offset from the center of a bar, as you can see in the following example:</p><pre>ggplot(diamonds) + <br>  # fill scales to 100%<br>  geom_bar(aes(x = clarity, fill = cut), position = &quot;fill&quot;) +<br>  scale_fill_manual(values = c(&quot;red&quot;, &quot;orange&quot;, &quot;darkgreen&quot;, &quot;dodgerblue&quot;, &quot;purple4&quot;)) +<br>  scale_y_continuous(labels = scales::percent) +<br>  labs(y = &quot;Percent of diamonds&quot;) +<br>  geom_hline(yintercept = 0.5, color = &quot;red&quot;, size = 1 ) +<br>  geom_vline(xintercept = 5.5, color = &quot;black&quot;, size = .5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sMrnD6CdNKGJ62uH" /></figure><p>This would be helpful if we wanted to especially point out differences between the last three clarity categories of diamonds compared to the other categories.</p><h3>7. Table</h3><p>While we have focused on figures here so far, tables can be incredibly informative at a glance too. If you are looking to display summary numbers, <strong>a table can also visually display information</strong>.</p><p>Using this same dataset, we can use a table to get a quick breakdown of how many males and females there are in the dataset and what percentage of each gender there is.</p><p>A few things to keep in mind when making tables is that it’s best to:</p><ul><li>Limit the number of digits in the table</li><li>Include a caption</li><li>When possible, keep it simple.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*f-jQwD-aW0KnMDhR" /></figure><p><em>Figure: Table</em></p><h4>7.1 Tables in R</h4><p>Now that we have a good understanding of what to consider when making tables, we can to practice making good tables in R. To do this, we’ll continue to use the diamonds dataset (which is part of the ggplot2 package). As a reminder, this dataset contains prices and other information about ~54,000 different diamonds. If we want to provide viewers with a summary of these data, we may want to provide information about diamonds broken down by the quality of the diamond’s cut. To get our data in the form we want we will use the dplyr package, which we discussed in a lesson earlier.</p><h4>7.2 Getting the Data in Order</h4><p>To start figuring out how the quality of the cut of the diamond affects the price of that diamond, we first have to get the data in order. To do that we’ll use the dplyr package. This allows us to group the data by the quality of the cut (cut) before summarizing the data to determine the number of diamonds in each category (N), the minimum price of the diamonds in this category (min), the average price (avg), and the highest price in the category (max).</p><p>To get these data in order, you could use the following code. This code groups the data by cut (quality of the diamond) and then calculates the number of diamonds in each group (N), the minimum price across each group (min), the average price of diamonds across each group (avg), and the maximum price within each group (max):</p><pre># get summary data for table in order<br>df &lt;- diamonds %&gt;% <br>  group_by(cut) %&gt;%<br>  dplyr::summarize(<br>    N = n(), <br>    min = min(price), <br>    avg = mean(price), <br>    max = max(price)<br>  )<br>## `summarise()` ungrouping output (override with `.groups` argument)</pre><h4>7.3 An Exploratory Table</h4><pre># look at data<br>df<br>## # A tibble: 5 x 5<br>##   cut           N   min   avg   max<br>##   &lt;ord&gt;     &lt;int&gt; &lt;int&gt; &lt;dbl&gt; &lt;int&gt;<br>## 1 Fair       1610   337 4359. 18574<br>## 2 Good       4906   327 3929. 18788<br>## 3 Very Good 12082   336 3982. 18818<br>## 4 Premium   13791   326 4584. 18823<br>## 5 Ideal     21551   326 3458. 18806</pre><p>By getting the data summarized into a single object in R (df), we’re on our way to making an informative table. However, this is clearly just an exploratory table. The output in R from this code follows some of the good table rules above, but not all of them. At a glance, it will help you to understand the data, but it’s not the finished table you would want to send to your boss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*ggr28M5zlFhEDh7D" /></figure><p><em>Figure: Exploratory diamonds table</em></p><p>From this output, you, the creator of the table, would be able to see that there are a number of <strong>good qualities</strong>:</p><ul><li>there is a <strong>reasonable number of rows and columns</strong> — There are 5 rows and 5 columns. A viewer can quickly look at this table and determine what’s going on.</li><li>the first column cut is <strong>organized logically</strong> — The lowest quality diamond category is first and then they are ordered vertically until the highest quality cut (ideal))</li><li>comparisons are made <strong>top to bottom</strong> — To compare between the groups, your eye only has to travel up and down, rather than from left to right.</li></ul><p>There are also things that <strong>need to be improved</strong> on this table:</p><ul><li><strong>column headers</strong> could be even more clear</li><li>there’s <strong>no caption/title</strong></li><li>it could be more <strong>aesthetically pleasing</strong></li></ul><h4>7.4 Improving the Table Output</h4><p>By-default, R outputs tables in the Console using a monospaced font. However, this limits our ability to format the appearance of the table. To fix the remaining few problems with the table’s format, we’ll use the kable() function from the R package knitr and the additional formatting capabilities of the R packages kableExtra.</p><p>The first step to a prettier table just involves using the kable() function from the knitr package, which improves the readability of this table. The knitr package is <em>not</em> a core tidyverse package, so you’ll have to be sure it’s installed and loaded.</p><pre># install.packages(&quot;knitr&quot;)<br>library(knitr)<br><br>kable(df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZ5xnp6RQGDuishVAjHFcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*aAh67pDqsrhSs6AQ" /></figure><p><em>Figure: kable basic output</em></p><p>However, there are still a few issues we want to improve upon:</p><ul><li>column names could be more informative</li><li>too many digits in the avg column</li><li>caption/title is missing</li><li>source of data not included</li></ul><p>To begin addressing these issues, we can use the add_header_above function from kableExtra() to specify that the min, avg, and max columns refer to price in US dollars (USD). Additionally, kable() takes a digits argument to specify how many significant digits to display. This takes care of the display of too many digits in the avg column. Finally, we can also style the table so that every other row is shaded, helping our eye to keep each row’s information separate from the other rows using kable_styling() from kableExtra. These few changes really improve the readability of the table.</p><p>If you copy this code into your R console, the formatted table will show up in the Viewer tab at the bottom right-hand side of your RStudio console and the HTML code used to generate that table will appear in your console.</p><pre># install.packages(&quot;kableExtra&quot;)<br>library(kableExtra)<br><br># use kable_styling to control table appearance<br>kable(df, digits=0, &quot;html&quot;) %&gt;%<br>  kable_styling(&quot;striped&quot;, &quot;bordered&quot;) %&gt;% <br>  add_header_above(c(&quot; &quot; = 2,  &quot;price (USD)&quot; = 3)) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/0*ZjlUb_OBs3HMsh7R" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*_Nq1a_hXCQpqU-Sn" /></figure><p>Figure: Viewer tab with formatted table</p><h4>7.5 Annotating Your Table</h4><p>We mentioned earlier that captions and sourcing your data are incredibly important. The kable package allows for a caption argument. Below, an informative caption has been included. Additionally, kableExtra has a footnote() function. This allows you to include the source of your data at the bottom of the table. With these final additions, you have a table that clearly displays the data and could be confidently shared with your boss.</p><pre>kable(df, digits=0, &quot;html&quot;, caption=&quot;Table 1: Diamonds Price by Quality of Cut. Most Diamonds are of the highest quality cut and the most expensive diamonds are of the highest quality&quot;) %&gt;%<br>  kable_styling(&quot;striped&quot;, &quot;bordered&quot;) %&gt;% <br>  # add headers and footnote<br>  add_header_above(c(&quot; &quot; = 2,  &quot;price (USD)&quot; = 3)) %&gt;% <br>  footnote(general = &quot;Diamonds dataset from ggplot2&quot;, general_title = &quot;Source:&quot;, footnote_as_chunk = T)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/0*NqkW7-gdLrSob-0R" /></figure><p><em>Figure: Viewer tab with annotated and formatted table</em></p><h3>8. GGPLOT2 Extensions</h3><h4>8.1.1 ggrepel</h4><p><a href="https://github.com/slowkow/ggrepel">ggrepel</a> “provides geoms for ggplot2 to repel overlapping text labels.”</p><p>To demonstrate the functionality within the ggrepel package and demonstrate cases where it would be needed, let’s use a dataset available from R — the mtcars dataset:</p><p>The data was extracted from the 1974 Motor Trend US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models).</p><p>This dataset includes information about 32 different cars. Let’s first convert this from a data.frame to a tibble. Note that we will keep the rownames and make it a new variable called model.</p><pre>mtcars &lt;- mtcars %&gt;%<br>as_tibble(rownames = &quot;model&quot;)</pre><p>What if we were to plot a scatterplot between horsepower (hp) and weight (wt) of each car and wanted to label each point in that plot with the care model.</p><p>If we were to do that with ggplot2, we’d see the following:</p><pre># label points without ggrepel<br>ggplot(mtcars, aes(wt, hp, label = model)) +<br>  geom_text() +<br>  geom_point(color = &#39;dodgerblue&#39;) +<br>  theme_classic()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*66QGLmwe7unIRfOC" /></figure><p>The overall trend is clear here — the more a car weights, the more horsepower it tends to have. However, many of the labels are overlapping and impossible to read — this is where ggrepel plays a role:</p><pre># install and load package<br># install.packages(&quot;ggrepel&quot;)<br>library(ggrepel)<br><br># label points with ggrepel<br>ggplot(mtcars, aes(wt, hp, label = model)) +<br>  geom_text_repel() +<br>  geom_point(color = &#39;dodgerblue&#39;) +<br>  theme_classic()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s2CwA_IO0JILKsVJ" /></figure><p>The only bit of code here that changed was that we changed geom_text() to geom_text_repel(). This, like geom_text() adds text directly to the plot. However, it also helpfully repels overlapping labels away from one another and away from the data points on the plot.</p><h4>8.1.2 Custom Formatting</h4><p>Within geom_text_repel(), there are a number of additional formatting options available. We’ll cover a number of the most important here, but the <a href="https://cran.r-project.org/web/packages/ggrepel/vignettes/ggrepel.html">ggrepel vignettes</a> explore these further.</p><h4>8.1.3 Highlighting Specific Points</h4><p>Often, you do not want to highlight <em>all</em> the points on a plot, but want to draw your viewer’s attention to a few <em>specific</em> points. To do this and say highlight only cars that are the make Mercedes, you could use the following approach:</p><pre>  theme(legend.position = &quot;none&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9TcE4WfV3TMeZWCS" /></figure><p>Here, notice that we first create a new column in our dataframe called merc. Here, we include the model of the car, only if “Merc” is in the model of the car’s name.</p><p>We then, specify that only these Mercedes cars should be labeled <em>and </em>that we only want them colored blue if they are Mercedes. This allows us to focus in on those few points we’re interested in. And, we can see that among the cars in this dataset, Mercedes tend to be of average weight but have varying horsepower, depending on the model of the car.</p><h4>8.1.4 Text Alignment</h4><p>Other times, you want to ensure that your labels are aligned on the top or bottom edge, relative to one another. This can be controlled using the hjust and vjust arguments. The values for particular alignment are:</p><p>hjust = 0 | to left-align hjust = 0.5 | to center hjust = 1 | to right-align</p><p>Additionally, you can adjust the starting position of text vertically with nudge_y (or horizontally with nudge_x). To use this, you’ll specify the distance from the point to the label you want to use.</p><p>You can also allow the labels to move horizontally with direction = “x” (or vertically with direction = “y”. This will put the labels at a right angle from the point. The default here is “both”, which allows labels to move in both directions.</p><p>For example, what if we wanted to plot the relationship between quarter mile time (qsec) and miles per gallon (mpg) to identify cars that get the best gas mileage.</p><p>To do this, we’re specifying within geom_text_repel() the following arguments:</p><p>data | only label those cars with gas mileage &gt; 30 mpg nudge_y | position all labels so that they’re vertically aligned hjust | center-align the labels direction | allow labels to move horizontally</p><p>For further customization, we’re also changing the segment color from the default black to a light gray (“gray60”).</p><pre># customize within geom_text_repel<br># first create a new column for mpg &gt; 30 within mtcars and pipe this into ggplot<br>mtcars %&gt;%<br>    mutate(mpg_highlight = case_when(mpg &gt; 30 ~&quot;high&quot;, mpg &lt; 30 ~ &quot;low&quot;)) %&gt;%<br>    ggplot(aes(qsec, mpg, label = model)) +<br>      geom_point(aes(color = mpg_highlight)) +<br>      scale_color_manual(values = c( &quot;dodgerblue&quot;, &quot;black&quot;)) +<br>      theme_minimal() +<br>      theme(legend.position = &quot;none&quot;) +<br>      geom_text_repel(data = mtcars %&gt;% filter(mpg &gt; 30), <br>        nudge_y = 3, <br>        hjust = 0.5, <br>        direction = &quot;x&quot;,<br>        segment.color = &quot;gray60&quot;) +<br>      scale_x_continuous(expand = c(0.05, 0.05)) +<br>      scale_y_continuous(limits = c(9, 38))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MrRb_DgMfLzkDDR5" /></figure><p>Notice that we’ve also had to provide the plot with more room by customizing the x- and y- axes, using the final two lines of code you see above.</p><p>With this plot, it is clear that there are four cars with mpg &gt; 30. And, among these, we now know that the Toyota Corolla has the slowest quarter mile time, all thanks to direct labeling of the points!</p><h4>8.2 directlabels</h4><p>The directlabels package also helps you to add labels directly to plots. There are functions that allow you to also add labels that generally dont overlap using less code than ggrepel, however there are less specification options.</p><p>There are several method options for adding direct labels to scatter plots, such as: first.points (which will place the label on the left in a scatterplot), and last.points (which will place the label on the right in a scatterplot).</p><pre>#install.packages(&quot;directlabels&quot;)<br>library(directlabels)<br><br>#first create a new column for mpg &gt; 30 within mtcars and pipe this into ggplot<br>mtcars %&gt;%<br>  mutate(mpg_highlight = case_when(mpg &gt; 30 ~ &quot;high&quot;, mpg &lt; 30 ~ &quot;low&quot;)) %&gt;%<br>  ggplot(aes(qsec, mpg, label = model)) +<br>  geom_point(aes(color = mpg_highlight)) +<br>  scale_color_manual(values = c(&quot;dodgerblue&quot;, &quot;black&quot;)) +<br>  scale_x_continuous(expand = c(0.05, 0.05)) +<br>  scale_y_continuous(limits = c(NA, 36)) +<br>  geom_dl(data = filter(mtcars, mpg &gt; 30), aes(label = model), <br>          method = list(c(&quot;first.points&quot;),<br>                        cex = 1)) +<br>  theme_minimal() +<br>  theme(legend.position = &quot;none&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h-bJNOfDALZCaH5J" /></figure><pre>mtcars %&gt;%<br>  mutate(mpg_highlight = case_when(mpg &gt; 30 ~ &quot;high&quot;, mpg &lt; 30 ~ &quot;low&quot;)) %&gt;%<br>  ggplot(aes(qsec, mpg, label = model)) +<br>  geom_point(aes(color = mpg_highlight)) +<br>  scale_color_manual(values = c(&quot;dodgerblue&quot;, &quot;black&quot;)) +<br>  scale_x_continuous(expand = c(0.05, 0.05)) +<br>  scale_y_continuous(limits = c(NA, 36)) +<br>  geom_dl(data = filter(mtcars, mpg &gt; 30), aes(label = model), <br>          method = list(c(&quot;last.points&quot;),<br>                        cex = 1)) +<br>  theme_minimal() +<br>  theme(legend.position = &quot;none&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fbujBMDE8zDTO_NH" /></figure><p>This package is especially useful for labeling lines in a lineplot. There are several methods, one of which is the angled.boxes method. This often negates the need for a legend.</p><pre>ggplot(mtcars, aes(qsec, mpg, color = cyl, group = cyl)) + <br>  geom_line()+<br>  geom_dl(aes(label = cyl), <br>          method = list(c(&quot;angled.boxes&quot;),<br>                        cex = 1)) +<br>  theme_minimal()+<br>  theme(legend.position = &quot;none&quot;) +<br>  labs(title = &quot;Differences in cars with 4, 6, or 8 cylinders&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BB3U-JJ23z6QVkDx" /></figure><p>See <a href="https://cran.r-project.org/web/packages/directlabels/directlabels.pdf">here</a> for more information about this package.</p><h4>8.3 cowplot</h4><p>Beyond customization within ggplot2 and labeling points, there are times you’ll want to arrange multiple plots together in a single grid, applying a standard theme across all plots. This often occurs when you’re ready to present or publish your visualizations. When you’re ready to share and present your work with others, you want to be sure your visualizations are conveying the point you want to convey to your viewer in as simple a plot as possible. And, if you’re presenting multiple plots, you typically want to ensure that they have a consistent theme from one plot to the next. This allows the viewer to focus on the data you’re plotting, rather than changes in theme. The cowplot package assists in this process!</p><h4>8.3.1 Theme</h4><p>The standard theme within cowplot, which works for many types of plots is theme_cowplot(). This theme is very similar to theme_classic(), which removes the background color, removes grid lines, and plots only the x- and y- axis lines (rather than a box around all the data). We’ll use this theme for the examples from this package. However, note that there are a number of additional themes available from the cowplot package. We will use the number 12 within this function to indicate that we want to use a font size of 12.</p><pre># install and load package<br># install.packages(&quot;cowplot&quot;)<br>library(cowplot)</pre><p>We’ll continue to use the mtcars dataset for these examples. Here, using the forcats package (which is part of the core tidyverse), we’ll add two new columns: transmission, where we recode the am column to be “automatic” if am == 0 and “manual” if am == 1, and engine, where we recode the vs column to be “v-shaped” if vs == 0 and “straight” if vs == 1.</p><pre>mtcars &lt;- mtcars %&gt;%<br>  mutate(transmission = fct_recode(as.factor(am), &quot;automatic&quot; = &quot;0&quot;, &quot;manual&quot; = &quot;1&quot;),<br>         engine = fct_recode(as.factor(vs), &quot;v-shaped&quot; = &quot;0&quot;, &quot;straight&quot; = &quot;1&quot;))</pre><p>We’ll use these data to generate a scatterplot plotting the relationship between 1/4 mile speed (qsec) and gas mileage (mpg). We’ll color the points by this new column transmission and apply theme_cowplot. Finally, we’ll assign this to p1, as we’ll ultimately generate a few different plots.</p><pre>p1 &lt;- ggplot(mtcars, aes(qsec, mpg, color = transmission)) + <br>  geom_point() +<br>  theme_cowplot(12) + <br>  theme(legend.position = c(0.7, 0.2))<br>p1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O0a_0sZzXanMxYsj" /></figure><p>Let’s make a similar plot, but color by engine type. We’ll want to manually change the colors here so that we aren’t using the same colors for transmission and engine. We’ll store this in p2.</p><pre>p2 &lt;- ggplot(mtcars, aes(qsec, mpg, color = engine)) + <br>  geom_point() +<br>  scale_color_manual(values = c(&quot;red&quot;, &quot;blue&quot;)) +<br>  theme_cowplot(12) +<br>  theme(legend.position = c(0.7, 0.2))<br>p2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cNcYNc8zv9ZO8pkP" /></figure><p>Great — we’ve now got two plots with the same theme and similar appearance. What if we wanted to combine these into a single grid for presentation purposes?</p><h4>8.3.2 Multiple Plots</h4><p>Combining plots is made simple within the cowplot package using the plot_grid() function:</p><pre># plot side by side<br>plot_grid(p1, p2, ncol = 2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Plhjrwxtk9wY-HS9" /></figure><p>Here, we specify the two plots we’d like to plot on a single grid and we also optionally include how many columns we’d like using the ncol parameter.</p><p>To plot these one on top of the other, you could specify for plot_grid() to use a single column.</p><pre># plot on top of one another<br>plot_grid(p1, p2, ncol = &quot;1&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FzCDsNBHmhI1scp_" /></figure><p>Note that by default, the plots will share the space equally, but it’s also possible to make one larger than the other within the grid using rel_widths and rel_heights.</p><p>For example, if you had a faceted plot summarizing the number of cars by transmission and engine (which we’ll call p3):</p><pre># generate faceted plot<br>p3 &lt;- ggplot(mtcars, aes(engine)) + <br>  geom_bar() + <br>  facet_wrap(~transmission) +<br>  scale_y_continuous(expand = expand_scale(mult = c(0, 0.1))) +<br>  theme_minimal_hgrid(12) +<br>  panel_border(color = &quot;black&quot;) +<br>  theme(strip.background = element_rect(fill = &quot;gray80&quot;))<br>## Warning: `expand_scale()` is deprecated; use `expansion()` instead.<br><br>p3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VcCXdTpfTo1xcEQa" /></figure><p>Note that for this plot we’ve chosen a different theme, allowing for horizontal grid lines. This can be helpful when visualizing bar plots.</p><p>If we were to plot these next to one another using the defaults, the faceted plot would be squished:</p><pre># plot next to one another<br>plot_grid(p1, p3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9qXOITsclPcTV7EK" /></figure><p>We can use rel_widths to specify the relative width for the plot on the left relative to the plot on the right:</p><pre># control relative spacing within grid<br>plot_grid(p1, p3, rel_widths = c(1, 1.3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rPjFXROYsaD0T0U1" /></figure><p>Notice how the plot on the left is now a bit more narrow and the plot on the right is a bit wider.</p><h4>8.3.3 Adding Labels</h4><p>Within these grids, you’ll often want to label these plots so that you can refer to them in your report or presentation. This can be done using the labels parameter within plot_grid():</p><pre># add A and B labels to plots<br>plot_grid(p1, p3, labels = &quot;AUTO&quot;, rel_widths = c(1, 1.3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uo6j3RhiNF7OFeK-" /></figure><h4>8.3.4 Adding Joint Titles</h4><p>Finally, when generating grids with multiple plots, at times you’ll often want a single title to explain what’s going on across the plots. Here, the process <em>looks</em> slightly confusing, but this is only because we’re putting all of these cowplot pieces together.</p><p>Generally, there are three steps:</p><ol><li>Create grid with plots</li><li>Create title object</li><li>Piece title and grid of plots together</li></ol><pre># use plot_grid to generate plot with 3 plots together<br>first_col &lt;- plot_grid(p1, p2, nrow = 2, labels = c(&#39;A&#39;, &#39;B&#39;))<br>three_plots &lt;- plot_grid(first_col, p3, ncol = 2, labels = c(&#39;&#39;, &#39;C&#39;), rel_widths = c(1, 1.3))<br><br># specify title<br>title &lt;- ggdraw() + <br>  # specify title and alignment<br>  draw_label(&quot;Transmission and Engine Type Affect Mileage and 1/4 mile time&quot;,<br>              fontface = &#39;bold&#39;, x = 0, hjust = 0) +<br>  # add margin on the left of the drawing canvas,<br>  # so title is aligned with left edge of first plot<br>  theme(plot.margin = margin(0, 0, 0, 7))<br><br># put title and plots togetner<br>plot_grid(title, three_plots, ncol = 1, rel_heights = c(0.1, 1))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lb9QJ8kMjrEk6qZU" /></figure><p>And, just like that we’ve got three plots, labeled, spaced out nicely in a grid, with a shared title, all thanks to the functionality within the cowplot package.</p><h4>8.4 patchwork</h4><p>The patchwork package is similar to the cowplot package in that they both are helpful for combining plots together. They each allow for different plot modifications, so it is useful to know about both packages.</p><p>With the patchwork package, plots can be combined using a few operators, such as “+”, “/”, and `“|”.</p><p>To combine two plots together we can simply add them together with the + sign or place them next to one another using the |:</p><pre>#install.packages(patchwork)<br>library(patchwork)<br>## <br>## Attaching package: &#39;patchwork&#39;<br>## The following object is masked from &#39;package:cowplot&#39;:<br>## <br>##     align_plots<br><br>p1 + p2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hlcTPvJwXrWg-EBb" /></figure><pre>p1 | p2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uEXH8tgZzERNwi2S" /></figure><p>If we want a plot above another plot we can use the “/” symbol:</p><pre>p1 / p2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jl4WI5gBrNkzd-Ei" /></figure><p>Grouping or nesting plots together using parenthesis can result in two or more plots taking up a single grid space.</p><p>Thus, to combine multiple plots in a more complicated layout, one can combine two plots on one row and have a third plot on another row like this:</p><pre>(p3 + p2) / p1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hhR6wguZrq6z3QIs" /></figure><p>Without the parentheses we would have the following:</p><pre>p3 + p2 / p1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1VaC-OceyOSp9mHG" /></figure><p>You can also empty plot spacers using the plotspacer() function like so:</p><pre>(plot_spacer() + p2 + plot_spacer()) / p1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JKAB6V2rmJNoZIeT" /></figure><p>You can modify the widths of the plots using the widths argument of the plot_layout() function. In the following example we will make the width of the plot on the left 2 times that of the plot on the right. Any numeric values will do, it is the ratio of the numbers that make the difference.</p><p>Thus, both p1 + p2 + plot_layout(widths = c(2, 1)) and p1 + p2 + plot_layout(widths = c(60, 30)) will result in the same relative size difference between p1 and p2.</p><pre>p1 + p2 + plot_layout(widths = c(2, 1))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zW8mB3ngdwBP4hsP" /></figure><pre>p1 + p2 + plot_layout(widths = c(60, 30))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZlPx8X1ZMWozvR4s" /></figure><p>The relative heights of the plots can also be modified using a heights argument with the same function.</p><pre>p1 + p2 + plot_layout(heights = c(2, 1))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lsfkgc6jrz7lOemj" /></figure><pre>p1 + p2 + plot_layout(heights = c(60, 30))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*37ezPW1VHuC3jFZs" /></figure><p>This package also allows for modification of legends. For example, legends can be gathered together to one side of the combined plots using the guides = ‘collect’ argument of the plot_layout() function.</p><pre>p1 + p2 + plot_layout(guides = &quot;collect&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VoqNuNYebRLKWT64" /></figure><p>You can also specify the number of columns or rows using this same function with ncol or nrow as you would with facet_wrap() of the ggplot2 package, where plots are added to <strong>complete a row</strong> before they will be added to a new row. For example, the following will result in an empty 2nd row below the plots.</p><pre>p1 + p2 + plot_layout(nrow = 2, ncol = 2, guides = &quot;collect&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wj7bk-_l8vmUHS0k" /></figure><p>However, the byrow = FALSE argument can disrupt this behavior and result in an empty 2nd column:</p><pre>p1 +p2 + plot_layout(nrow = 2, ncol = 2, byrow = FALSE, guides = &quot;collect&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*utPK9ok1CLysgVz1" /></figure><p>In this case the <strong>columns will be preferentially completed</strong> before placing a plot in a new column.</p><p>We can also use the package to change the theme specifications of specific plots. By default the plot just prior to the theme() function will be the only plot changed.</p><pre>p1 + p2 + theme(legend.position = &quot;bottom&quot;) + p2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vA6OSaylpWNt8_wF" /></figure><p>Using the *, themes can be added to all plots that are nested together.</p><pre>(p1 + p2) *theme_bw() + p2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bwv3Lwgkq3W-mxB1" /></figure><p>The &amp; adds themes to all plots.</p><pre>(p1 + p2) + p2 &amp; theme(axis.title.x = element_text(face = &quot;bold&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-76UjxXMBO8rUneG" /></figure><p>Annotations for all the plots combined can also be added using the plot_annotation() function, which can also take theme() function specifications with the theme argument.</p><pre>(p1 + p2) + p3 + theme(axis.text.x = element_text(angle = 90)) +<br>  plot_annotation(title = &quot;Plot title for all 3 plots&quot;, <br>                  theme = theme(plot.title = element_text(hjust = 0.5)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3dxcTsYIvtswu87X" /></figure><p>See <a href="https://patchwork.data-imaginist.com/">here</a> for more information about the patchwork package.</p><h4>8.5 gganimate</h4><p>The final ggplot2 extension we’ll discuss here is <a href="https://gganimate.com/">gganimate</a>. This extends the grammar of graphics implemented in the ggplot2 package to work with animated plots. To get started, you’ll need to install and load the package:</p><pre>library(gganimate)</pre><p>The gganimate package adds functionality by providing a number of these grammar classes. Across the animation being generated, the following classes are made available, with each classes’ corresponding functionality:</p><ul><li>transition_*() | specifies how data should transition</li><li>enter_*()/exit_*() | specifies how data should appear and disappear</li><li>ease_aes() | specifies how different aesthetics should be eased during transitions</li><li>view_*() | specifies how positional scales should change</li><li>shadow_*() | specifies how points from a previous frame should be displayed in current frame</li></ul><p>We’ll walk through these grammar classes using the mtcars dataset.</p><h4>8.5.1 Example: mtcars</h4><p>As noted, gganimate builds on top of the functionality within ggplot2, so the code should look pretty familiar by now.</p><p>First, using the mtcars dataset we generate a static boxplot looking at the relationship between the number of cylinders a car has (cyl) and its gas mileage (mpg).</p><pre># generate static boxplot<br>ggplot(mtcars) + <br>  geom_boxplot(aes(factor(cyl), mpg))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0gv7gIX5faYY6NMT" /></figure><p>But what if we wanted to understand the relationship between those two variables and the number of gears a car has (gear)?</p><p>One option would be to use faceting:</p><pre># facet by gear<br>ggplot(mtcars) + <br>  geom_boxplot(aes(factor(cyl), mpg)) +<br>  facet_wrap(~gear)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mCkDCk37fsh5TqBf" /></figure><p>Alternatively, we could animate the plot, using gganimate so that on a single plot we rotate between each of these three plots.</p><h4>8.5.2 Transitions</h4><p>We’ll transition in this example between frames by gear:</p><pre># animate it!<br>mtcars %&gt;%<br>  mutate(gear = factor(gear),<br>         cyl = factor(cyl)) %&gt;%<br>  ggplot() + <br>  geom_boxplot(aes(cyl, mpg)) + <br>  transition_manual(gear)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VgbLkTpOTUG34_hD" /></figure><p>Note that here, transition_manual() is a new grammar class that we add right on top of our ggplot2 plot code! Within this grammar class, we specify the variable upon which we’d like the transition in the animation to occur.</p><p>This means that the number of frames in the animation will be the number of levels in the variable by which you’re transitioning. Here, there will be 3 frames, as there are three different levels of gear in the mtcars dataset.</p><p>transition_manual() is not the only option for transition. In fact, there are a number of different transition_* options, depending upon your animation needs. One of the most commonly used is transition_states(). The animation will plot the same information as the example above; however, it allows for finer tune control of the animation</p><pre># animate it!<br>anim &lt;- ggplot(mtcars) + <br>  geom_boxplot(aes(factor(cyl), mpg)) + <br>  transition_states(gear,<br>                    transition_length = 2,<br>                    state_length = 1)<br><br>anim</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RHlXKwI00Cb9pC20" /></figure><p>Note here that we’ve stored the output from transition_states in the object anim. We’ll build on this object below.</p><h4>8.5.3 Labeling</h4><p>Currently, it’s hard to know which frame corresponds to which gear. To make this easier on the viewer, let’s label our animation:</p><pre># animate it!<br>anim &lt;- anim +  <br>  labs(title = &#39;Now showing gear: {closest_state}&#39;)<br><br>anim</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rsu9wLnLDQIMCuEv" /></figure><p>Note that we’re referring to the appropriate gear within the animation frame by specifying {closest_state}.</p><h4>8.5.4 Easing</h4><p>Easing determines how the change from one value to another should occur. The default is linear, but there are other options that will control the appearance of progression in your animation. for example, ‘cubic-in-out’ allows for the start and end of the animation to have a smoother look.</p><pre>anim &lt;- anim + <br>  # Slow start and end for a smoother look<br>  ease_aes(&#39;cubic-in-out&#39;)<br><br>anim</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H5vQeg-0WSRyEBPF" /></figure><p>There are a number of easing functions, all of which are listed within the documentation, which can be viewed, as always, using the ? help function: ?ease_aes.</p><h4>8.5.5 Enter &amp; Exit</h4><p>Building on top of easing, we can also control how the data appears (enters) and disappears (exits), using enter_* and exit_*:</p><pre>anim &lt;- anim + <br>  # fade to enter<br>  enter_fade() +<br>  # shrink on exit<br>  exit_shrink()<br><br>anim</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*56X0ZIIfwLAeEXvp" /></figure><p>The changes are subtle but you’ll notice that on transition the data fades in to appear and shrinks upon exit.</p><h4>8.5.6 Position Scales</h4><p>To demonstrate how changing positional scales can be adjusted, let’s take a look at a scatterplot. Here, we’re plotting the relationship between 1/4 mile speed and miles per gallon and we’ll be transitioning between gear.</p><p>The static plot would be as follows:</p><pre>ggplot(mtcars) + <br>  geom_point(aes(qsec, mpg))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lc0QFzTc9LqDhhWv" /></figure><p>However, upon adding animation, we see how the data changes by gear.</p><pre># animate it!<br>scat &lt;- ggplot(mtcars) + <br>  geom_point(aes(qsec, mpg)) + <br>  transition_states(gear,<br>                    transition_length = 2,<br>                    state_length = 1) +<br>    labs(title = &#39;Now showing gear: {closest_state}&#39;)<br><br>scat</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BefP0HV4mbq14p0l" /></figure><p>However, the x- and y-axes remain constant throughout the animation.</p><p>If you wanted to allow these positional scales to adjust between each gear level, you could use view_step:</p><pre># allow positional scaling for each level in gear<br>scat +<br>  view_step(pause_length = 2, <br>            step_length = 1, <br>            nsteps = 3, <br>            include = FALSE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wk6yiSsKUQtxpoho" /></figure><h4>8.5.7 Example: gapminder</h4><p>One of the most famous examples of an animated plot uses the gapminder dataset. This dataset includes economic data for countries all over the world. The animated plot here demonstrates the relationship between GDP (per capita) and life expectancy over time, by continent. Note that the year whose data is being displayed is shown at the top left portion of the plot.</p><pre># install.packages(&quot;gapminder&quot;)<br>library(gapminder)<br><br>gap &lt;- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +<br>  geom_point(alpha = 0.7, show.legend = FALSE) +<br>  scale_colour_manual(values = country_colors) +<br>  scale_size(range = c(2, 12)) +<br>  scale_x_log10() +<br>  facet_wrap(~continent, ncol = 5) +<br>  theme_half_open(12) +<br>  panel_border() + <br>  # animate it!<br>  labs(title = &#39;Year: {frame_time}&#39;, x = &#39;GDP per capita&#39;, y = &#39;life expectancy&#39;) +<br>  transition_time(year)<br><br>gap</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eo4c7FbDWxsxbMjo" /></figure><p>Note that in this example, we’re now using transition_time() rather than transition_states(). This is a variant of transition_states() that is particularly useful when the states represent points in time, such as the years we’re animating through in the plot above. The transition length is set to correspond to the time difference between the points in the data.</p><h4>8.5.8 Shadow</h4><p>However, what if we didn’t want the data to completely disappear from one frame to the next and instead wanted to see the pattern emerge over time? We didn’t demonstrate this using the mtcars dataset because each observation in that dataset is a different car. However, here, with the gapminder dataset, where we’re looking at a trend over time, it makes more sense to include a trail.</p><p>To do this, we would use shadow_*. Here, we’ll use shadow_trail() to see a trail of the data from one frame to the next:</p><pre>gap +<br> shadow_trail(distance = 0.05,<br>              alpha = 0.3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pwiUHGKin784R-SL" /></figure><p>Here, distance specifies the temporal distance between the frames to show and alpha specifies the transparency of the trail, so that the current frame’s data is always discernible.</p><h3>9. Conclusion</h3><p>Data visualization is not merely a presentation layer but a fundamental analytical instrument that bridges raw data and actionable insight. As demonstrated, effective visualization within the ggplot2 ecosystem is grounded in a structured grammar — where data, geoms, and aesthetic mappings are systematically composed to produce meaningful representations.</p><p>A critical distinction emerges between exploratory and explanatory visualizations: the former supports cognitive sense-making and hypothesis generation, while the latter is optimized for precise communication and decision support. This duality reinforces that visualization is not a one-size-fits-all process but a staged pipeline aligned with analytical intent.</p><p>Moreover, the choice of plot type, color encoding, labeling, and scaling is not merely aesthetic — it directly impacts interpretability, cognitive load, and the risk of misrepresentation. Poor design decisions (e.g., misleading axes, inappropriate chart types, or perceptually ineffective color schemes) can distort insights, whereas principled design enhances clarity, trust, and analytical rigor.</p><p>From a systems perspective, the layered architecture of ggplot2 embodies a compositional paradigm that aligns with modular data science workflows. Each layer incrementally refines the visualization, enabling reproducibility, extensibility, and abstraction — properties essential for scalable analytical pipelines.</p><p>In summary, mastering data visualization requires more than technical proficiency; it demands an understanding of perception, communication theory, and data semantics. When executed rigorously, visualization becomes a powerful interface between data and cognition — transforming complex datasets into interpretable, trustworthy, and decision-ready knowledge artifacts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf68134aaa10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Tidyverse: Lecture-01]]></title>
            <link>https://medium.com/@ai.mlresearcher/introduction-to-tidyverse-lecture-01-a3041ed09c36?source=rss-a9253868464d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3041ed09c36</guid>
            <category><![CDATA[tidyverse]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Syed Hamed Raza]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 05:34:29 GMT</pubDate>
            <atom:updated>2026-03-30T05:34:29.466Z</atom:updated>
            <content:encoded><![CDATA[<h4>General Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5jGvSvfFzFJ9IP4O" /><figcaption>Photo by <a href="https://unsplash.com/@tvannoy?utm_source=medium&amp;utm_medium=referral">Trevor Vannoy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. What is the Tidyverse</h3><p>The <strong>Tidyverse</strong> is not just a library; it is a <strong>coherent computational paradigm</strong> for structuring the entire data science pipeline.</p><h4>Core idea:</h4><blockquote><em>Enforce </em><strong><em>consistent data representation + composable transformations</em></strong></blockquote><p>This eliminates:</p><ul><li>ad-hoc scripting</li><li>inconsistent data formats</li><li>fragmented workflows</li></ul><h3>2. The Central Abstraction: Tidy Data</h3><p>The entire ecosystem is built around one formal constraint:</p><h4>Tidy Data Definition</h4><p>A dataset is <em>tidy</em> if:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*AJd9YNlfsJP7T97DkOMeyQ.png" /></figure><h4>Example: Non-Tidy vs Tidy</h4><h4>Non-Tidy Data (Wide / Messy)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*5CUS0e5t7ffdTgwzRYFREQ.png" /></figure><p>Problem:</p><ul><li>“Subject” is encoded in <strong>column names</strong></li><li>Violates feature representation consistency</li></ul><h4>Tidy Data (Long Format)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*tAkrsTHs2UMa0xSanMd4pQ.png" /></figure><p>Now:</p><ul><li>“Subject” becomes a <strong>feature (column)</strong></li><li>Enables grouping, modeling, and visualization</li></ul><h3>3. Why Tidy Data Matters</h3><p>From a <strong>machine learning / statistical perspective</strong>:</p><ul><li>Models assume:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*hmxrwFbQMbycjNzVj_etvg.png" /></figure><ul><li>where:</li><li>rows = observations</li><li>columns = features</li></ul><p>Tidy data <strong>aligns directly with this matrix representation</strong></p><h3>4. Data Science Lifecycle (Tidyverse Perspective)</h3><p>The paragraph implicitly refers to a pipeline. Formally</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*QwXxa4lHMMfhtMnmxAVAwA.png" /></figure><p>Mapped to Tidyverse:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*QfOZBCJ0wWKBVxqWmPraEA.png" /></figure><h3>5. R + Tidyverse Example</h3><h4>Step 1: Create Non-Tidy Data</h4><pre>library(tidyverse)<br>data &lt;- tibble(<br>  student = c(&quot;Ali&quot;, &quot;Sara&quot;),<br>  math = c(80, 90),<br>  english = c(70, 85)<br>)<br>data<br><br>## # A tibble: 2 × 3<br>##   student  math english<br>##   &lt;chr&gt;   &lt;dbl&gt;   &lt;dbl&gt;<br>## 1 Ali        80      70<br>## 2 Sara       90      85</pre><h4>Step 2: Convert to Tidy Data</h4><pre>tidy_data &lt;- data %&gt;%<br>  pivot_longer(<br>    cols = c(math, english),<br>    names_to = &quot;subject&quot;,<br>    values_to = &quot;marks&quot;<br>  )<br><br>tidy_data<br><br>## # A tibble: 4 × 3<br>##   student subject marks<br>##   &lt;chr&gt;   &lt;chr&gt;   &lt;dbl&gt;<br>## 1 Ali     math       80<br>## 2 Ali     english    70<br>## 3 Sara    math       90<br>## 4 Sara    english    85</pre><h4>Step 3: Analyze (Group + Summary)</h4><pre>tidy_data %&gt;%<br>  group_by(subject) %&gt;%<br>  summarise(avg_marks = mean(marks))<br><br>## # A tibble: 2 × 2<br>##   subject avg_marks<br>##   &lt;chr&gt;       &lt;dbl&gt;<br>## 1 english      77.5<br>## 2 math         85</pre><h4>Step 4: Visualize</h4><pre>ggplot(tidy_data, aes(x = subject, y = marks, fill = subject)) +<br>  geom_bar(stat = &quot;identity&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fweHTmqa7KgDuzHfkQdKnA.png" /></figure><h3>6. What is Actually “Revolutionary” Here?</h3><p>This claim in the text is not marketing — it has <strong>technical grounding</strong>:</p><h4>Traditional R (Base R)</h4><ul><li>Imperative</li><li>Inconsistent APIs</li><li>Hard to chain operations</li></ul><h4>Tidyverse</h4><ul><li>Functional + declarative</li><li>Pipe operator (%&gt;%)</li><li>Grammar-based transformations</li></ul><h4>Example Comparison</h4><p><strong>Base R</strong></p><pre>aggregate(marks ~ subject, data = tidy_data, mean)<br>##   subject marks<br>## 1 english  77.5<br>## 2    math  85.0</pre><p><strong>Tidyverse</strong></p><pre>tidy_data %&gt;%<br>  group_by(subject) %&gt;%<br>  summarise(mean = mean(marks))<br>## # A tibble: 2 × 2<br>##   subject  mean<br>##   &lt;chr&gt;   &lt;dbl&gt;<br>## 1 english  77.5<br>## 2 math     85</pre><p>The second aligns with <strong>dataflow thinking</strong></p><h3>7. For Beginners vs Experts (Important Distinction)</h3><h4>For Beginners</h4><ul><li>Provides <strong>structured mental model</strong></li><li>Reduces cognitive load</li><li>Teaches pipeline thinking</li></ul><h4>For Experts</h4><ul><li>Enables:</li><li>reproducibility</li><li>composability</li><li>integration with ML pipelines</li></ul><h3>8. Key Teaching Insight</h3><p>The <em>real takeaway</em> is not tools — it is:</p><blockquote><strong><em>Data representation governs everything downstream</em></strong></blockquote><h3>9. Compact Summary</h3><ul><li>Tidyverse = <strong>pipeline-oriented data science framework</strong></li><li>Core idea = <strong>tidy data (row = instance, column = feature)</strong></li><li>Enables transformation, visualization, and modeling</li><li>Acts as a <strong>unified interface across the lifecycle</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3041ed09c36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative AI]]></title>
            <link>https://medium.com/@ai.mlresearcher/generative-ai-73466cacac8c?source=rss-a9253868464d------2</link>
            <guid isPermaLink="false">https://medium.com/p/73466cacac8c</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Syed Hamed Raza]]></dc:creator>
            <pubDate>Fri, 15 Aug 2025 10:18:48 GMT</pubDate>
            <atom:updated>2025-08-15T10:18:48.848Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Primer for the Age of Augmented Intelligence</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IcK6Dm5WozUY6Zb4" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Introduction to Generative AI and Why It Matters</h3><p>Generative AI is a branch of artificial intelligence that can create new content — whether text, images, video, or even music — based on instructions from a user. While traditional AI often focuses on recognizing patterns or making predictions, generative AI <em>produces</em> original material.</p><p>Only a few years ago, the idea of having an AI like ChatGPT — capable of conversing naturally, producing creative writing, generating code, or designing unique visuals — seemed far-fetched. Yet, it arrived unexpectedly, transforming how we think about technology.</p><p>To understand generative AI, think of it like sending a message to a very talented “digital collaborator.” You type a request (this is called a <strong>prompt</strong>), and instead of a human replying, the AI sends back text, an image, or other media. The AI’s reply is called the <strong>output</strong>.</p><p>Generative AI is a new class of technology that creates original content in response to human prompts. It has quickly shifted from an impossible idea to an everyday reality.</p><p>Imagine you had a magic mailbox. You write a letter saying, “Draw me a castle floating in the clouds,” put it in the mailbox, and within seconds, a perfectly illustrated picture arrives back. Generative AI is that magic mailbox — except it can send back almost anything you ask for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VilkrSlnTWwhGJn016GDcQ.png" /></figure><h3>2. Rethinking How We Use Generative AI</h3><p>Many headlines portray AI as “failing” when it gives imperfect results, but this mindset misses the point. Generative AI isn’t meant to deliver a flawless one-shot answer — it’s more like working with an assistant. You give them a task, review their work, provide feedback, and refine it together.</p><p>The process should be <strong>iterative</strong>:</p><ol><li>Send an initial prompt.</li><li>Get a draft back.</li><li>Give feedback or adjustments.</li><li>Repeat until satisfied.</li></ol><p>Judging AI on its first attempt is like giving a sculptor a new chisel, asking for a statue, and quitting after the first chip of stone doesn’t look like the final masterpiece.</p><blockquote>Generative AI works best through conversation and refinement, not one-off questions. Its value comes from collaboration, not perfection on the first try.</blockquote><p>Think of AI like a junior chef in your kitchen. The first dish might not be perfect, but if you guide them — “less salt,” “more spice,” “make it vegetarian” — they’ll quickly adapt and create something you’ll enjoy.</p><h3>3. Complex, Creative Problem-Solving with AI</h3><p>Generative AI excels at tasks that would be hard to assign to a single human expert. For example, you could ask it to design a weekly meal plan combining the cuisines of two countries, tailored to a specific diet, and restricted to ingredients from a local store. That’s a lot of constraints for a human to juggle quickly — but AI can draft it in seconds.</p><p>Once you have that draft, you can request specific serving sizes, swap ingredients, or adapt the menu for different preferences. The magic lies in how easily you can evolve the original idea through simple follow-up prompts.</p><blockquote>Generative AI can tackle multi-layered, highly specific problems in seconds, producing a base that can be customized and refined.</blockquote><p>It’s like having a travel planner who instantly gives you a detailed itinerary for a vacation that mixes hiking, local cuisine, and historical sites — then immediately adjusts it if you say, “Make it pet-friendly and add a cooking class.”</p><h3>4. Adding Personalization and Engagement</h3><p>AI’s capabilities aren’t limited to information — it can create engaging, personalized experiences. For example, if you want a child to try new foods, you could ask AI to invent fun stories or games linked to the meal. It could weave characters, adventures, and cliff-hangers into the dinner experience, turning an ordinary task into something interactive and exciting.</p><p>This isn’t just about novelty — it’s about using creativity to solve practical challenges in ways that weren’t easily possible before.</p><blockquote>Generative AI can inject creativity and personalization into everyday activities, making them more engaging and effective.</blockquote><p>Imagine getting your child to clean their room by turning it into a “treasure hunt” story generated by AI, where every toy they put away reveals a new clue to a hidden adventure.</p><h3>5. From Conversation to Working Software</h3><p>The same iterative conversation you use to create content can also produce functioning software. You could design a learning game in the chat, then ask the AI to write code for it in a programming language like Python. In minutes, you could have an interactive program running on a device — no formal coding session needed.</p><p>This process dramatically accelerates creativity: start with a simple idea, refine it into a story or game, and then turn it into working software without switching tools or starting from scratch.</p><blockquote>Generative AI bridges the gap between ideas and functional products, enabling non-experts to create working software from conversational instructions.</blockquote><p>It’s like explaining a board game idea to a friend who instantly builds you a playable digital version, complete with rules, graphics, and scoring.</p><h3>6. The Bigger Picture</h3><p>Generative AI represents a leap in what humans can accomplish with technology. Just a year ago, many of these capabilities weren’t generally available to the public. Today, anyone with an internet connection can access them.</p><p>The real power comes when humans drive the process — AI doesn’t replace creativity or critical thinking, it amplifies it. With the right approach, these tools can expand our productivity, solve complex problems, and open up entirely new ways of working and learning.</p><blockquote>Generative AI is a powerful amplifier of human creativity and problem-solving, and its best results come from active, thoughtful collaboration with the user.</blockquote><p>Think of it as a high-powered exoskeleton — not walking for you, but letting you lift, run, and climb far beyond your natural limits.</p><h3>7. Generative AI Is Changing the Way We Use Computers</h3><p>For decades, our main way of interacting with computers has been through <strong>graphical user interfaces (GUIs)</strong> — clicking on menus, buttons, and icons — or through programming, which requires time, effort, and specialized skills. GUIs are easy but limited to what the software designer provided. Programming is flexible but slow and costly.</p><p>Generative AI is changing that balance. It’s becoming a <strong>new interface</strong> for computing — one that combines the flexibility of programming with the accessibility of a GUI. Instead of learning a programming language or hunting for the right menu, you can simply <strong>describe what you want in natural language</strong> and let the AI figure out how to make it happen.</p><blockquote>Generative AI is emerging as a new, natural-language interface to computing, replacing many tasks previously done through GUIs or programming.</blockquote><p>Think of computing like ordering food:</p><ul><li>GUI = browsing a fixed restaurant menu.</li><li>Programming = cooking everything from scratch.</li><li>Generative AI = telling a personal chef exactly what you want, and they make it — whether it’s on the “menu” or not.</li></ul><h3>8. From Policies to Practical Answers</h3><p>Traditionally, applying organizational policies (like travel expense rules) meant reading long documents or relying on specialists to interpret them. With generative AI, you can simply <strong>upload the policy document</strong> and ask your real-world question — such as whether a specific travel cost is reimbursable.</p><p>The AI doesn’t just summarize — it applies the rules to your specific situation, even noting where the policy is silent. This turns static policy documents into <strong>interactive, searchable knowledge systems</strong> that work instantly and without manual setup.</p><blockquote>AI can transform static policy documents into dynamic, on-demand advisors that answer real-world questions accurately and contextually.</blockquote><p>It’s like having a 24/7 corporate lawyer who has memorized every company policy and can instantly tell you, “Yes, you can do that — here’s the exact paragraph that allows it.”</p><h3>9. Turning Documents into Action</h3><p>Generative AI isn’t limited to answering questions — it can act on documents. You can upload a receipt and ask if it complies with your company’s policy. The AI can cross-reference the policy, flag potential violations, and explain its reasoning.</p><p>Before generative AI, this required custom-built rules engines, expensive software, or manual review. Now, it’s just a matter of <strong>providing the document and a well-phrased request</strong>.</p><blockquote>Generative AI can apply rules to real data without custom programming, enabling instant compliance checks and decision support.</blockquote><p>Imagine a referee who reads the rulebook once and can then officiate any game — calling fouls accurately, even in unusual situations.</p><h3>10. Extracting and Transforming Data Effortlessly</h3><p>Extracting data from complex PDFs or reports used to be tedious. With generative AI, you can upload a report and request that each page be saved as a text file, turned into an Excel sheet, or visualized as charts — all without leaving the chat.</p><p>Instead of manually copying, pasting, and formatting data, you can focus on <strong>interpreting and communicating insights</strong>, letting AI handle the grunt work.</p><blockquote>Generative AI removes the manual effort from data extraction, conversion, and visualization, allowing users to focus on analysis.</blockquote><p>It’s like having an assistant who, upon receiving a box of paper invoices, instantly hands you a clean spreadsheet with summaries, totals, and charts — ready for your presentation.</p><h3>11. Automating Presentations and Reports</h3><p>Once AI generates visualizations, you can go a step further — upload a PowerPoint template and ask it to insert each visualization as a slide, complete with descriptive text.</p><p>Here’s the key: the AI doesn’t just manipulate data — it can <strong>build its own tools</strong> on the fly. When creating the presentation, it may write a Python script internally to generate images and insert them into slides, then delete the script after use.</p><blockquote>Generative AI can create custom tools in real time to complete complex multi-step tasks — like generating a ready-to-present slide deck from raw data.</blockquote><p>It’s like hiring a handyman who, upon realizing they need a special wrench for your job, forges one in their workshop, uses it once, and then returns to finish the work without you ever noticing the extra step.</p><h3>12. The Bigger Shift: AI as a General-Purpose Interface</h3><p>What makes these capabilities transformative is that AI can dynamically create and use software tools to meet your needs — without you having to learn programming. This <strong>lowers the barrier to advanced computing</strong> for everyone, not just engineers.</p><p>While GUIs and programming will remain important, generative AI is poised to become a dominant interface for many computing tasks. It allows everyday users to perform work that once required specialized skills, dramatically accelerating productivity and innovation.</p><blockquote>Generative AI is making advanced computing capabilities accessible to all, shifting the role of humans from “software operators” to “idea drivers.”</blockquote><p>It’s like moving from driving a manual car to giving verbal directions to a self-driving vehicle — freeing you to focus on where you want to go, not how to operate the machine.</p><h3>13. Rethinking the Text Box</h3><p>When people first encounter generative AI, they often treat its text box like a search engine: type a question, get a factual answer. But this mental model is flawed.</p><p>Search engines are designed to retrieve facts. Generative AI, on the other hand, is designed to produce original content, solutions, or reasoning based on your request. Judging it only by its factual accuracy misses the point — it’s more like a collaborator than a library.</p><p>Another misconception is that we can type anything, in any form, and expect perfect results. In reality, <strong>the quality of your input strongly influences the quality of the output</strong>. Just like working with a human colleague, unclear or incomplete instructions can lead to disappointing results.</p><blockquote>Generative AI is not a search engine. It’s a collaborative tool where your input shapes the quality and usefulness of the output.</blockquote><p>It’s like talking to a skilled contractor — you wouldn’t just say “build me something” and expect your dream house. You’d explain the design, purpose, and features you want.</p><h3>14. Understanding How Large Language Models Learn</h3><p>Large language models (LLMs) like ChatGPT are trained to predict the next word in a sentence. They do this billions of times on vast amounts of text, gradually learning patterns in language and how words relate to each other.</p><p>For example, if the model sees “Mary had a little,” it predicts “lamb” based on patterns it has learned. This is repeated with different starting points — “Mary had a little lamb its…” might lead to “fleece,” and so on. Over time, the model becomes skilled at generating coherent and contextually appropriate language.</p><p>This training process is the foundation for <strong>prompt engineering</strong> — the art and science of crafting inputs that guide the model toward useful outputs.</p><blockquote>LLMs are trained to predict words based on patterns in text. Understanding this helps you design prompts that guide the model toward better results.</blockquote><p>Think of it like a jazz musician who has practiced so much that they can improvise smoothly, because they’ve internalized the patterns and rhythms of countless songs.</p><h3>15. Prompt Engineering as a Discipline</h3><p>Prompt engineering isn’t just about clever wording — it’s a broad skillset that includes structuring requests, validating results, maintaining accuracy over time, and even creating reusable prompt “architectures.”</p><p>Just like software engineering involves everything from code syntax to system design, prompt engineering covers the micro (wording) and macro (strategies, workflows, and best practices) of working effectively with generative AI.</p><blockquote>Prompt engineering is a structured discipline that goes beyond wording, covering strategies, validation, and reusability.</blockquote><p>It’s like cooking: knowing the recipe is important, but so is understanding how to source ingredients, adjust for dietary needs, and present the final dish attractively.</p><h3>16. Prompt Patterns as Building Blocks</h3><p>One way to teach prompt engineering is through <strong>prompt patterns</strong> — reusable templates for solving different types of problems. These patterns are like common formats in everyday communication. For example, a formal letter often starts with “Dear [Name],” followed by the message body.</p><p>By documenting these prompt patterns, teams can quickly apply proven approaches in their own context, reducing trial and error.</p><blockquote>Prompt patterns are reusable formats that make it easier to solve problems consistently and creatively.</blockquote><p>Think of them as Lego bricks — you can snap them together in different ways to build entirely new creations.</p><h3>17. The Persona Pattern</h3><p>The <strong>persona pattern</strong> is one of the most powerful prompt patterns. You instruct the AI to “act as” a specific role — such as a nutritionist, lawyer, chief security officer, or teacher.</p><p>By defining a role, you give the AI context for its responses, allowing it to draw on relevant reasoning and vocabulary. This can surface insights you might not even know to request.</p><p>For instance, asking it to “act as a speech language pathologist” and evaluate a child’s speech sample can produce a detailed, professional-style assessment — even including concepts you didn’t explicitly request, such as “consonant cluster reduction.”</p><blockquote>The persona pattern lets AI adopt specialized viewpoints, generating richer, more relevant outputs.</blockquote><p>It’s like hiring an actor to play a doctor in a role — they’ll speak and behave in ways consistent with that profession, even if you didn’t script every detail.</p><h3>18. Teaching Prompt Patterns for Workforce Skills</h3><p>To prepare people for working effectively with generative AI, we should teach prompt patterns systematically — starting with foundational ones like the persona pattern. Once mastered, these can be adapted to different fields, enabling employees to lead innovation within their departments.</p><p>Rather than dumping hundreds of example prompts on users, giving them structured, reusable patterns empowers them to create their own high-quality prompts tailored to their work.</p><blockquote>Teaching prompt patterns equips the workforce with transferable skills to use AI effectively and creatively in their roles.</blockquote><p>It’s like teaching people the grammar of a language instead of just giving them phrases to memorize — they’ll be able to express anything they need.</p><h3>19. Programming Without Code</h3><p>Traditionally, programming means writing code in languages like Python or Java, but generative AI introduces a new approach: <strong>programming with prompts</strong>. Instead of crafting detailed instructions in code, you can simply describe the rules or behavior you want in plain language, and the AI will execute them.</p><p>For example, you can say, “Whenever you generate output, format it as a CSV list.” Without specifying column names, the AI can infer them from context. If you want to change the format later — such as adding a “Role” column — you just update your prompt. You’re essentially editing the “program” by changing the rules in natural language.</p><blockquote>With generative AI, anyone can “program” by describing desired behavior in plain language, making computing far more accessible.</blockquote><p>It’s like telling a smart assistant, “Every time you write a shopping list for me, organize it by category,” and later adding, “Also include estimated prices.” No need to rewrite any code or learn technical commands.</p><h3>20. Adding Advanced Capabilities Through Prompts</h3><p>This prompt-based programming isn’t limited to simple formatting. You can instruct the AI to generate <strong>synthetic examples</strong>, perform data mapping, or convert free text (like survey responses or product reviews) into structured formats like CSV or JSON.</p><p>These capabilities would have required complex natural language processing pipelines in the past. Now, they can be created instantly by refining your prompt.</p><blockquote>Prompt programming can incorporate advanced logic and data transformation that used to require specialized software.</blockquote><p>It’s like asking a translator not only to convert a sentence into another language but also to reformat it into a table, highlight key terms, and create similar example sentences — all in one step.</p><h3>21. Building a Personal Email Assistant with Prompts</h3><p>One powerful use case is managing long email threads. You can create a “program” by telling the AI:</p><ul><li>When given an email thread, list questions and action items as numbered bullets.</li><li>If I type a bullet’s number, summarize that part of the conversation.</li><li>If I type a bullet’s number and a paragraph count, draft a reply of that length.</li></ul><p>After pasting a lengthy email chain into the conversation, the AI instantly produces an actionable summary and can zoom in on specific items for detailed context or draft responses.</p><blockquote>Generative AI can be prompted to act as a fully functional, custom-built assistant for complex workflows like email triage — without writing a single line of code.</blockquote><p>It’s like hiring an assistant who not only organizes your meeting notes into a task list but can also instantly brief you on any single task or draft a response for you, just by you giving a short command.</p><h3>22. Two Key Shifts in Computing</h3><p>Generative AI is ushering in two major revolutions:</p><ol><li><strong>Unique computational capabilities</strong> — It can interpret context, infer meaning, and transform unstructured data in sophisticated ways (e.g., deducing group consensus from an email thread).</li><li><strong>A new interface to computing</strong> — Instead of code or GUIs, natural language can now be used to build and control applications, lowering the barrier to entry for powerful computing.</li></ol><p>These shifts mean that everyday users, not just programmers, can create tools and processes that were once highly technical.</p><blockquote>Generative AI combines powerful new capabilities with a natural language interface, enabling non-programmers to build sophisticated tools.</blockquote><p>It’s like replacing a complex control panel with a conversation — you just tell the system what you want, and it builds the buttons and switches it needs behind the scenes to make it happen.</p><h3>23. Augmented Intelligence, Not Replacement</h3><p>The most valuable vision for generative AI isn’t to replace people — it’s to amplify them. Think of it as an <strong>exoskeleton for the mind</strong>, giving you extra strength in creativity, problem-solving, and productivity while preserving what makes you uniquely human.</p><p>Instead of automating away meaningful work, this approach frees people from repetitive, low-value tasks so they can spend more time thinking critically, creating, and interacting with others.</p><blockquote>Generative AI should be used to enhance human abilities, not replace them, enabling people to focus on high-value, creative, and interpersonal work.</blockquote><p>It’s like upgrading a bicycle to an electric-assist model — it doesn’t ride for you, but it makes uphill climbs faster and easier so you can enjoy the journey.</p><h3>24. The ACHIEVE Framework</h3><p>To guide responsible and effective use of generative AI, the <strong>ACHIEVE</strong> framework offers seven principles:</p><ol><li><strong>Aid human coordination</strong> — Improve collaboration and clarity.</li><li><strong>Cut out tedious tasks</strong> — Free up mental bandwidth for creative and strategic work.</li><li><strong>Help provide a safety net</strong> — Catch mistakes before they cause problems.</li><li><strong>Inspire better problem-solving and creativity</strong> — Spark fresh ideas and approaches.</li><li><strong>Enable great ideas to scale faster</strong> — Turn concepts into large-scale initiatives quickly.</li></ol><p>The “IEV” in ACHIEVE is emphasized because inspiring and enabling humans to think better is central to this vision.</p><blockquote>The ACHIEVE framework offers a structured way to use generative AI to support, enhance, and scale human work effectively.</blockquote><p>It’s like a multi-tool — different functions, one purpose: to make you more capable and adaptable in a variety of situations.</p><h3>24. Aid Human Coordination</h3><p>AI can improve team coordination by identifying ambiguities in meeting notes or project plans. For example, after uploading a meeting transcript, you could ask: “List any ambiguities in our plan.” The AI might point out missing deadlines or unclear responsibilities, helping the team align before small issues become big problems.</p><p>It can even suggest <strong>who should follow up</strong> based on who was mentioned in the transcript, ensuring the right person handles the right task.</p><blockquote>Generative AI can detect and help resolve unclear points in team communication, improving coordination and accountability.</blockquote><p>It’s like having a project manager who, after every meeting, highlights unclear action items and assigns them to the right people automatically.</p><h3>25. Cut Out Tedious Tasks</h3><p>Many workplace tasks — like sorting survey responses — are repetitive but necessary. AI can categorize free-text answers into themes instantly, and you can quickly try multiple groupings to discover new patterns without the manual drudgery.</p><p>By removing the busywork, you can focus on interpreting the results and deciding how to act on them.</p><blockquote>Generative AI eliminates repetitive manual work, enabling faster analysis and more time for creative decision-making.</blockquote><p>It’s like having an assistant who organizes all your receipts into neat folders while you focus on planning your next business strategy.</p><h3>26. Provide a Safety Net</h3><p>AI can act as a second set of eyes — catching technical terms in your slides that your audience might not know, or spotting conflicting decisions between teams before they cause delays.</p><p>This “prevention-first” approach helps avoid costly errors, whether in software integration or event logistics.</p><blockquote>Generative AI can proactively identify potential mistakes, acting as an early warning system.</blockquote><p>It’s like a proofreader who doesn’t just check grammar but also spots inconsistencies in your argument before you publish.</p><h3>27. Inspire Creativity and Better Problem-Solving</h3><p>Humans are prone to biases in problem-solving — falling back on familiar approaches. AI can help by offering diverse, unexpected ideas.</p><p>For example, if a workshop needs childcare, AI could design lesson plans that teach kids about large language models using Pokémon-themed activities. These ideas serve as starting points for humans to refine and build upon.</p><p>You can also ask the AI to act as a skeptic, generating hard questions about your presentation to help you prepare for challenges.</p><blockquote>Generative AI can spark fresh thinking and challenge your assumptions, leading to stronger, more creative solutions.</blockquote><p>It’s like brainstorming with someone from a completely different field — they’ll suggest things you never would have considered.</p><h3>28. Enable Great Ideas to Scale</h3><p>Scaling creative ideas often requires more capacity than one person has. For instance, you could use AI to draft personalized post-event emails for attendees, each containing a tailored prompt relevant to their field.</p><p>By letting the AI handle the domain-specific brainstorming, you can scale personalization and engagement far beyond what would be possible manually.</p><blockquote>Generative AI enables rapid scaling of personalized, high-impact ideas without increasing workload proportionally.</blockquote><p>It’s like having a marketing team of 50 people at your disposal, instantly tailoring content for every customer segment.</p><h3>29. The Path to Mastery in Generative AI</h3><p>To unlock the full potential of generative AI, you need to master <strong>prompt engineering</strong> — the skill of crafting instructions that guide AI to produce the results you want.</p><p>A few key learning resources:</p><ul><li><strong>Prompt Engineering Course (Coursera)</strong> — Over 150,000 learners have used it to explore prompt techniques across fields like finance, marketing, art, and law.</li><li><strong>ChatGPT Advanced Data Analysis Course</strong> — Despite its name, this tool is not just for data scientists. It’s an automation platform for tasks like generating PowerPoint decks, creating data visualizations, or answering questions from uploaded documents.</li><li><strong>Innovative Teaching with ChatGPT</strong> — Practical examples for educators, including lesson planning, example creation, and assessment design.</li><li><strong>Prompt Pattern Catalog (Research Paper)</strong> — A freely available paper documenting reusable “prompt patterns” to accelerate innovation in any field.</li></ul><blockquote>The fastest way to become proficient with generative AI is to systematically learn prompt engineering and automation tools, using structured courses and pattern libraries as guides.</blockquote><p>It’s like learning to play a musical instrument: you start with techniques (prompt patterns), then learn to improvise (creative applications), and finally join a band (collaborative, real-world use cases).</p><h3>30. A Closing Vision: Augmented, Not Replaced</h3><p>The future of generative AI is about <strong>amplifying human capability</strong>, not replacing it. The “exoskeleton for the mind” vision means using AI to:</p><ul><li>Scale creative ideas quickly.</li><li>Spend more time on meaningful human interaction.</li><li>Focus on critical thinking and innovation rather than routine tasks.</li></ul><p>The <strong>ACHIEVE</strong> framework remains central: use AI to coordinate, automate, catch errors, inspire ideas, and scale them — while keeping humans in control.</p><p>The goal is to nurture and amplify the <strong>unique human spark</strong> in each person, building a future where technology serves as a partner rather than a substitute.</p><blockquote>Generative AI should be a tool for human amplification, enabling more creativity, deeper connections, and faster execution of big ideas.</blockquote><p>It’s like having a skilled co-pilot — your journey is still yours to steer, but they make sure you fly higher, faster, and safer than you could alone.</p><h3><strong>31. Conclusion</strong></h3><p>Generative AI marks a fundamental shift in the way humans interact with technology. It’s more than a tool for automation — it’s a partner for creativity, problem-solving, and innovation. When used with intention, it can break down barriers to advanced computing, empower individuals in every field, and accelerate the journey from idea to impact.</p><p>The future is not about machines replacing people, but about humans equipped with powerful, intuitive AI — working together to achieve more than either could alone. By embracing frameworks like ACHIEVE, honing prompt engineering skills, and committing to responsible, human-centered use, we can ensure this technology becomes an exoskeleton for the mind — amplifying the very qualities that make us human.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73466cacac8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-Powered Tools for Students: From Project Idea Generation to Programming Language Comparisons…]]></title>
            <link>https://levelup.gitconnected.com/ai-powered-tools-for-students-from-project-idea-generation-to-programming-language-comparisons-50300e9e334a?source=rss-a9253868464d------2</link>
            <guid isPermaLink="false">https://medium.com/p/50300e9e334a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Syed Hamed Raza]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 06:50:13 GMT</pubDate>
            <atom:updated>2025-08-11T03:27:00.656Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI-Powered Tools for Students: From Project Idea Generation to Programming Language Comparisons Using LangChain and OpenAI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vNrHIfOzOp3nxLXX" /><figcaption>Photo by <a href="https://unsplash.com/@iseeworld?utm_source=medium&amp;utm_medium=referral">Matt Wang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Introduction</h3><p>Over the past decade, Artificial Intelligence (AI) has transitioned from research labs to everyday tools, reshaping how students learn, collaborate, and solve problems. Large Language Models (LLMs), such as OpenAI’s GPT family, have been at the forefront of this transformation. Their ability to process, analyze, and generate human-like text has opened the door to countless educational applications.</p><p>For students, the possibilities are vast: brainstorming project ideas, summarizing research, explaining concepts, comparing technologies, and more. However, simply having access to an LLM isn’t enough. To unlock its full potential, we need a framework that enables structured, reusable, and easy-to-maintain interaction. <strong>LangChain</strong> is one such framework.</p><p>In this article, we’ll walk through two AI-powered tools built with <strong>LangChain</strong> and the <strong>OpenAI API</strong> that are particularly useful for students:</p><ol><li><strong>Project Idea Generator</strong>: Generate five innovative and practical final-year project ideas in a specific subject.</li><li><strong>Programming Language Comparison Tool: </strong>Compare two programming languages for a given purpose, analyzing their strengths, weaknesses, and suitability.</li></ol><p>We’ll cover:</p><ul><li>The technologies involved</li><li>How the code works</li><li>Example outputs</li><li>Why these tools matter</li><li>Potential extensions for even greater usefulness</li></ul><p>By the end, you’ll understand not only how the code works but also how to adapt it for your own learning or teaching context.</p><h3>2. Why LLM-Based Tools Are Important for Students</h3><p>Students often face two common challenges:</p><ol><li><strong>Finding good project ideas</strong><br> Many students struggle to choose a topic for their final-year project. The idea must be innovative enough to stand out, but also feasible within their time and resource constraints. Searching online for “final-year project ideas” often results in outdated, repetitive, or overly generic suggestions.</li><li><strong>Choosing the right technology</strong><br> Whether it’s selecting a programming language for a project or a framework for implementation, students are often overwhelmed by choices. Without prior experience, it’s hard to know which tool is most suitable for their needs.</li></ol><p>LLM-powered tools can address both problems:</p><ul><li>They can generate <strong>fresh, context-aware ideas</strong> that match the latest industry and academic trends.</li><li>They can provide <strong>structured comparisons</strong> between technologies, helping students make informed decisions.</li></ul><h3>3. The Technology Stack</h3><p>Before diving into the code, let’s briefly cover the main technologies:</p><h4>1. OpenAI API</h4><p>The OpenAI API provides programmatic access to powerful language models like gpt-3.5-turbo, gpt-4o, and gpt-4o-mini. You can prompt these models to generate, analyze, and transform text in a conversational style.</p><h4><strong>Why use OpenAI?</strong></h4><ul><li>High-quality text generation</li><li>Flexible control over creativity (via temperature)</li><li>Support for various models optimized for speed, accuracy, or cost</li></ul><h3>4. LangChain</h3><p>LangChain is a Python framework designed to simplify working with LLMs. It provides:</p><ul><li><strong>PromptTemplate: </strong>A way to structure prompts with placeholders for variables.</li><li><strong>Chains: </strong>A pipeline that links prompts, LLMs, and other components.</li><li><strong>Integrations: </strong>Ready-made connections to APIs, databases, and tools.</li></ul><p>Instead of sending plain strings to the OpenAI API, LangChain lets us build structured, reusable workflows.</p><h3>5. Python</h3><p>We’re using Python because:</p><ul><li>It’s widely taught in universities</li><li>It has excellent support for AI libraries</li><li>It’s easy to read and maintain</li></ul><h3>6. The Code: Two Tools in One</h3><p>We’ve built <strong>two separate functions</strong>, each leveraging LangChain and OpenAI in different ways.</p><h3>7. Project 01: Idea Generator</h3><p><strong>Purpose:</strong> Generate 5 innovative and practical final-year project ideas for students in a specific field.</p><h4>How It Works:</h4><ul><li>The user specifies a subject (e.g., <em>Artificial Intelligence</em>, <em>Cybersecurity</em>, <em>Data Science</em>).</li><li>The prompt template instructs the LLM to produce 5 project ideas, each with a short description.</li><li>The LLM is configured with a <strong>high temperature (0.85)</strong> to encourage creative and diverse outputs.</li></ul><pre>from langchain_openai import ChatOpenAI<br>from langchain.prompts import PromptTemplate<br>import os<br><br>os.environ[&quot;OPENAI_API_KEY&quot;] = &quot;YOUR_OPENAI_API_KEY&quot;<br><br>llm_creative = ChatOpenAI(<br>    model=&quot;gpt-4o-mini&quot;,<br>    temperature=0.85  # Higher = more creative output<br>)<br><br>def generate_project_ideas(subject: str) -&gt; str:<br>    prompt = PromptTemplate(<br>        input_variables=[&quot;subject&quot;],<br>        template=&quot;Generate 5 innovative and practical final-year project ideas for students in the field of {subject}. &quot;<br>                 &quot;Include a short description for each idea.&quot;<br>    )<br>    chain = prompt | llm_creative<br>    response = chain.invoke({&quot;subject&quot;: subject})<br>    return response.content<br><br>print(&quot;=== AI Project Ideas ===&quot;)<br>print(generate_project_ideas(&quot;Artificial Intelligence&quot;))</pre><pre>=== AI Project Ideas ===<br>Here are five innovative and practical final-year project ideas for students in the field of Artificial Intelligence:<br><br>1. **AI-Driven Personal Health Assistant**<br>   - **Description**: Develop a mobile application that utilizes AI algorithms to analyze user health data collected from wearables (like heart rate, steps, sleep quality) and recommends personalized health and wellness plans. The app can use natural language processing (NLP) to understand user queries and provide insights on diet, exercise, and mental health, along with reminders for medication and appointments.<br><br>2. **Automated Plant Disease Detection System**<br>   - **Description**: Create a machine learning model capable of identifying diseases in plants from images taken by users using their smartphones. By training the model on a dataset of healthy and diseased plant images, the application can provide instant feedback and potential solutions for treatment, allowing farmers and gardeners to take immediate action to save their crops.<br><br>3. **Smart Traffic Management System**<br>   - **Description**: Design an AI-based traffic management system that analyzes real-time traffic data from cameras and sensors installed at intersections. The system can optimize traffic light timers and suggest alternate routes to drivers to reduce congestion and improve traffic flow. Incorporate predictive analytics to foresee traffic patterns based on historical data and special events in the area.<br><br>4. **AI-Powered Accessibility Tool for the Visually Impaired**<br>   - **Description**: Develop an application that uses computer vision and speech recognition to assist visually impaired users in navigating their surroundings. The tool can provide real-time audio descriptions of nearby objects, obstacles, and text, allowing users to better understand their environment. Implement features like object recognition, pathfinding, and crowd detection to enhance user experience and safety.<br><br>5. **Intelligent Content Recommendation System for E-Learning Platforms**<br>   - **Description**: Build a recommendation engine tailored for e-learning platforms that uses collaborative filtering and content-based filtering techniques to suggest courses, articles, and resources based on user behavior and preferences. The system can leverage Natural Language Processing to analyze course content and create personalized learning paths that adapt as the student progresses, leading to improved engagement and retention.<br><br>These projects not only emphasize the utilization of AI technologies but also address real-world issues, making them practical and impactful for students in their final year.</pre><p><strong>Why Students Love This Tool:</strong><br> It saves hours of brainstorming and provides cutting-edge ideas aligned with industry needs.</p><h3>8. Project 02: Programming Language Comparison Tool</h3><p><strong>Purpose:</strong> Compare two programming languages for a specific purpose and give a detailed breakdown.</p><h4>How It Works:</h4><ul><li>The user specifies two languages and a purpose (e.g., <em>Python vs Java for AI development</em>).</li><li>The prompt template guides the LLM to compare them based on ease of learning, community support, available libraries, performance, and suitability.</li><li>The LLM is configured with a <strong>low temperature (0.4)</strong> to produce more factual, consistent responses.</li></ul><pre>from langchain.chat_models import ChatOpenAI<br>from langchain.prompts import PromptTemplate<br><br>os.environ[&quot;OPENAI_API_KEY&quot;] = &quot;YOUR_OPENAI_API_KEY&quot;<br><br>llm_factual = ChatOpenAI(<br>    model=&quot;gpt-4o-mini&quot;,<br>    temperature=0.4  # Lower = more factual, less random<br>)<br><br>def compare_programming_languages(lang1: str, lang2: str, purpose: str) -&gt; str:<br>    prompt = PromptTemplate(<br>        input_variables=[&quot;lang1&quot;, &quot;lang2&quot;, &quot;purpose&quot;],<br>        template=&quot;Compare the programming languages {lang1} and {lang2} for the purpose of {purpose}. &quot;<br>                 &quot;Discuss ease of learning, community support, available libraries, performance, and suitability.&quot;<br>    )<br>    chain = prompt | llm_factual<br>    response = chain.invoke({<br>        &quot;lang1&quot;: lang1,<br>        &quot;lang2&quot;: lang2,<br>        &quot;purpose&quot;: purpose<br>    })<br>    return response.content<br><br>print(&quot;\n=== Programming Language Comparison ===&quot;)<br>print(compare_programming_languages(&quot;Python&quot;, &quot;Java&quot;, &quot;AI development&quot;))</pre><pre>=== Programming Language Comparison ===<br>When comparing Python and Java for AI development, several factors come into play, including ease of learning, community support, available libraries, performance, and overall suitability for AI tasks. Here’s a detailed comparison:<br><br>### 1. Ease of Learning<br>- **Python**: Python is widely regarded as one of the easiest programming languages to learn, especially for beginners. Its syntax is clean and readable, which allows new developers to focus on concepts rather than complex syntax. This is particularly advantageous in AI, where understanding algorithms and models is more critical than mastering language intricacies.<br>  <br>- **Java**: Java has a steeper learning curve compared to Python. Its syntax is more verbose, and it requires understanding of concepts like object-oriented programming and memory management. While Java is still accessible to beginners, it may take longer to become proficient compared to Python.<br><br>### 2. Community Support<br>- **Python**: Python has a large and active community, particularly in the fields of data science and AI. There are numerous forums, tutorials, and resources available, making it easier for developers to find help and learn from others’ experiences.<br><br>- **Java**: Java also has a strong community, especially in enterprise environments. While there are many resources available, the focus is less on AI and more on general software development, web applications, and enterprise solutions.<br><br>### 3. Available Libraries<br>- **Python**: Python excels in the availability of libraries specifically designed for AI and machine learning. Libraries such as TensorFlow, PyTorch, Keras, Scikit-learn, and NumPy provide extensive functionalities for building and deploying AI models. The ease of integration with data manipulation libraries like Pandas also enhances its suitability for AI tasks.<br><br>- **Java**: Java has libraries for AI development, such as Weka, Deeplearning4j, and MOA, but they are not as widely adopted or as comprehensive as Python’s offerings. Java’s libraries tend to be more focused on traditional programming paradigms rather than the rapid prototyping and experimentation that Python facilitates.<br><br>### 4. Performance<br>- **Python**: While Python is generally slower than Java in terms of execution speed due to its interpreted nature, many AI libraries are built on optimized C/C++ code, which mitigates performance concerns for many applications. However, for compute-intensive tasks, Python may not be the best choice without careful optimization.<br><br>- **Java**: Java typically offers better performance due to its compiled nature and the efficiency of the Java Virtual Machine (JVM). For applications where performance is critical, such as large-scale systems or real-time processing, Java may be more suitable.<br><br>### 5. Suitability for AI Development<br>- **Python**: Python is the dominant language for AI and machine learning development. Its simplicity, extensive libraries, and strong community support make it the go-to choice for researchers and developers in the field. Python’s flexibility allows for rapid prototyping and experimentation, which is crucial in AI development.<br><br>- **Java**: While Java can be used for AI development, it is more commonly used in enterprise-level applications and large systems. Its strengths lie in robustness, scalability, and maintainability, making it suitable for building large-scale AI systems where performance and reliability are paramount. However, it may not be the first choice for research or rapid development.<br><br>### Conclusion<br>In summary, **Python** is generally preferred for AI development due to its ease of learning, extensive libraries, and strong community support. It is particularly suited for rapid prototyping and research. **Java**, while capable and offering better performance in some scenarios, is less commonly used in the AI domain and is better suited for enterprise applications where stability and scalability are critical. For developers focused on AI, Python is the clear choice, while Java may be more appropriate in contexts where performance and integration with existing systems are prioritized.</pre><p><strong>Why Students Love This Tool:</strong><br> It provides a clear, unbiased breakdown, helping them make informed technology choices for their projects.</p><h3>9. Benefits for Students</h3><h4>1. Time Savings</h4><p>Instead of spending days brainstorming or comparing tech, students get answers in seconds.</p><h4>2. Exposure to Current Trends</h4><p>LLMs are trained on vast amounts of information, so the suggestions are aligned with modern industry practices.</p><h4>3. Decision Support</h4><p>Clear comparisons help students select the best tools for their projects.</p><h4>4. Learning Aid</h4><p>Even if a student doesn’t choose the generated ideas, reading them sparks new thought processes.</p><h3>10. Possible Extensions</h3><ol><li><strong>Integrate Real-Time Web Search</strong><br> Connect LangChain’s search tools to fetch up-to-date rankings, new technologies, or research papers.</li><li><strong>Generate Output as JSON</strong><br> Instead of plain text, structure the results in JSON so they can be displayed in web apps or stored in databases.</li><li><strong>Multi-Language Support</strong><br> Let students get project ideas or comparisons in Urdu or any other language.</li><li><strong>Add Feasibility Scores</strong><br> For each project idea, include a complexity and cost score so students can choose based on constraints.</li><li><strong>Interactive CLI or Web Interface</strong><br> Wrap these functions in a Flask/Django web app or a command-line tool for easy access.</li></ol><h3>11. Challenges and Considerations</h3><p>While these tools are powerful, they also come with caveats:</p><ul><li><strong>Factual Accuracy: </strong>LLMs can sometimes “hallucinate” facts. For technical comparisons, verify results from authoritative sources.</li><li><strong>Over-Reliance: </strong>Students should use these tools for inspiration, not as a substitute for their own research and creativity.</li><li><strong>API Costs: </strong>Frequent use of the OpenAI API can be costly, especially with larger models.</li></ul><h3>12. Educational Impact</h3><p>For educators, these tools:</p><ul><li>Can be integrated into coursework for teaching research and technology evaluation.</li><li>Serve as examples in AI programming classes.</li><li>Demonstrate prompt engineering concepts in practice.</li></ul><p>For students, they:</p><ul><li>Provide a head start in the ideation process.</li><li>Offer a structured way to evaluate technologies.</li><li>Build familiarity with AI tools, which are increasingly part of professional workflows.</li></ul><h3>13. Conclusion</h3><p>By combining LangChain’s structured workflow approach with OpenAI’s powerful language models, we can create practical, impactful tools that directly address student needs. The <strong>Project Idea Generator</strong> and <strong>Programming Language Comparison Tool</strong> are just two examples of what’s possible.</p><p>These tools save time, inspire creativity, and help students make informed decisions skills that are essential in both academic and professional settings.</p><p>In the near future, we can expect even more sophisticated AI-powered educational assistants: tools that combine real-time web search, academic database integration, and personalized learning recommendations. For now, mastering these fundamental integrations is a great first step toward building your own intelligent educational applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50300e9e334a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/ai-powered-tools-for-students-from-project-idea-generation-to-programming-language-comparisons-50300e9e334a">AI-Powered Tools for Students: From Project Idea Generation to Programming Language Comparisons…</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Problem-Solving Agents]]></title>
            <link>https://medium.com/@ai.mlresearcher/problem-solving-agents-f7ef414ce79a?source=rss-a9253868464d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7ef414ce79a</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Syed Hamed Raza]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 10:41:44 GMT</pubDate>
            <atom:updated>2025-03-23T10:41:44.294Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Deep Dive into Intelligent Decision-Making</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JWr7ppylxla0NgpX" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Introduction</h3><p>One of the central challenges in Artificial Intelligence (AI) is enabling machines to <strong>solve problems intelligently</strong>. Whether it’s a robot navigating a maze, a system playing a game of chess, or an app planning an optimal delivery route, the ability to solve problems is at the heart of what it means to act intelligently.</p><p>To approach such challenges, AI systems often take the form of <strong>problem-solving agents</strong> — intelligent agents designed to make decisions that move them closer to achieving specific goals. This article explores the concept of problem-solving agents in depth, covering their structure, functioning, environment assumptions, classical examples, and practical applications. The discussion is rooted in the formal models presented by Russell and Norvig.</p><h3>2. What is a Problem-Solving Agent?</h3><p>A <strong>problem-solving agent</strong> is an intelligent agent that decides what to do by finding a sequence of actions that leads to the desired goal. Unlike reactive agents that respond to current percepts, problem-solving agents use <strong>search</strong> and <strong>planning</strong> to determine actions that are effective over time.</p><h3>2.1. Definition</h3><blockquote><strong><em>A problem-solving agent is a goal-based agent that decides what actions to take by formulating problems and searching for solutions.</em></strong></blockquote><p>The agent uses a model of the environment to simulate future states and select action sequences that lead to desirable outcomes.</p><h3>3. The Structure of a Problem-Solving Agent</h3><p>A problem-solving agent has the following structure:</p><ol><li><strong>Goal formulation</strong>: Define what it wants to achieve.</li><li><strong>Problem formulation</strong>: Translate the goal into a formal problem.</li><li><strong>Search</strong>: Explore possible actions to find a solution.</li><li><strong>Execution</strong>: Apply the chosen actions in the real world.</li></ol><h4>3.1. Goal Formulation</h4><p>The first step is to define the <strong>goal</strong>. A goal is a desired state that the agent wishes to reach. Goals must be:</p><ul><li><strong>Well-defined</strong></li><li><strong>Achievable</strong></li><li><strong>Measurable</strong></li></ul><p>For example, for a delivery robot, the goal might be “Deliver the package to Building B.”</p><h4>3.2. Problem Formulation</h4><p>Once a goal is set, the agent formulates the problem using the following components:</p><ul><li><strong>Initial State</strong>: Where the agent starts.</li><li><strong>Actions (Successor Function)</strong>: What can be done from a given state.</li><li><strong>Transition Model</strong>: Describes the result of performing an action.</li><li><strong>Goal Test</strong>: Determines whether the goal has been reached.</li><li><strong>Path Cost</strong>: Measures the cost of a path (e.g., distance, time).</li></ul><h4>3.3. Search for Solutions</h4><p>The agent uses search algorithms to find a path from the initial state to a goal state. This step involves:</p><ul><li>Building a <strong>search tree</strong></li><li>Exploring nodes (states)</li><li>Evaluating paths using cost or heuristics</li></ul><h4>3.4. Execution</h4><p>Finally, the agent executes the selected sequence of actions to achieve the goal. It may replan if the environment changes unexpectedly.</p><h3>4. Assumptions in Classical Problem-Solving</h3><p>Problem-solving agents typically operate under <strong>classical assumptions</strong>:</p><ol><li><strong>Fully Observable</strong>: The agent can access the complete state of the environment.</li><li><strong>Deterministic</strong>: The outcome of actions is predictable.</li><li><strong>Episodic/Static</strong>: The environment doesn’t change while the agent is thinking.</li><li><strong>Discrete</strong>: There are a finite number of possible states and actions.</li><li><strong>Single-Agent</strong>: No other agents affect the environment.</li></ol><p>These assumptions simplify the problem and make search-based solutions feasible.</p><h3>5. Examples of Classic Problems</h3><p>To understand problem-solving agents in action, we explore classic examples frequently used in AI research and teaching.</p><h4>5.1. Vacuum Cleaner World</h4><p>The <strong>vacuum world</strong> is a simple environment where the agent must clean a two-room world.</p><ul><li><strong>States</strong>: Agent’s location and status (clean/dirty) of each room.</li><li><strong>Actions</strong>: Move left, move right, suck dirt.</li><li><strong>Goal</strong>: Clean both rooms.</li><li><strong>Solution</strong>: A sequence of moves that results in both rooms being clean.</li></ul><p>Despite its simplicity, this environment introduces concepts like state representation and action effects.</p><h4>5.2. 8-Puzzle Problem</h4><p>This is a classic tile-sliding puzzle:</p><ul><li><strong>State</strong>: 3x3 grid with tiles numbered 1–8 and one blank space.</li><li><strong>Actions</strong>: Move the blank space up, down, left, or right.</li><li><strong>Goal</strong>: Reach a target configuration.</li><li><strong>Path Cost</strong>: Usually the number of moves.</li></ul><p>It exemplifies search in a finite but large state space.</p><h4>5.3. 8-Queens Problem</h4><p>Place 8 queens on a chessboard such that none attack each other.</p><ul><li><strong>State</strong>: Board configurations with queens placed.</li><li><strong>Actions</strong>: Place a queen in a row/column.</li><li><strong>Goal</strong>: No two queens threaten each other.</li><li><strong>Challenge</strong>: Large branching factor and constraints.</li></ul><p>This is an example of a <strong>constraint satisfaction problem</strong>.</p><h3>6. The Search Tree</h3><p>Problem-solving agents search through a <strong>search tree</strong>:</p><ul><li><strong>Nodes</strong>: Represent states.</li><li><strong>Edges</strong>: Represent actions.</li><li><strong>Root Node</strong>: Initial state.</li><li><strong>Goal Node</strong>: Desired end state.</li></ul><p>The agent explores the tree using a specific <strong>search strategy</strong> to find the optimal or satisfactory path.</p><h3>7. Problem Types</h3><p>There are several categories of problems that determine which search methods and agent types are appropriate:</p><h4>7.1. Single-State vs. Multiple-State Problems</h4><ul><li><strong>Single-State</strong>: Agent knows exactly where it is.</li><li><strong>Multiple-State</strong>: Agent is unsure and must consider multiple possibilities.</li></ul><h4>7.2. Observable vs. Hidden Information</h4><ul><li><strong>Observable</strong>: All relevant information is accessible.</li><li><strong>Hidden</strong>: Some parts of the state are unknown.</li></ul><h4>7.3. Static vs. Dynamic Environments</h4><ul><li><strong>Static</strong>: Environment remains unchanged while solving.</li><li><strong>Dynamic</strong>: Environment can change unpredictably.</li></ul><h3>8. Uninformed Search Strategies</h3><p>These are search methods that <strong>do not use domain-specific knowledge</strong>. They rely only on the problem definition.</p><h4>8.1. Breadth-First Search (BFS)</h4><ul><li>Explores nodes level by level.</li><li>Complete and optimal (for uniform cost).</li><li>Time/space complexity: O(b^d)</li></ul><h4>8.2. Uniform-Cost Search (UCS)</h4><ul><li>Expands the least-cost node.</li><li>Optimal and complete.</li></ul><h4>8.3. Depth-First Search (DFS)</h4><ul><li>Explores as deep as possible before backtracking.</li><li>Not optimal or complete (can get stuck in infinite paths).</li><li>Space-efficient.</li></ul><h4>8.4. Iterative Deepening Search (IDS)</h4><ul><li>Combines BFS and DFS advantages.</li><li>Complete, optimal, and space-efficient.</li></ul><h3>9. Informed Search (Heuristic Search)</h3><p>These strategies use additional information (heuristics) to guide the search.</p><h4>9.1. Greedy Best-First Search</h4><ul><li>Chooses the node that appears closest to the goal.</li><li>Not always optimal.</li></ul><h4>9.2. A Search*</h4><ul><li>Uses: f(n) = g(n) + h(n)</li><li>g(n): Cost so far</li><li>h(n): Heuristic estimate</li><li><strong>Admissible Heuristic</strong>: Never overestimates</li><li><strong>Consistent Heuristic</strong>: Monotonic</li></ul><p><strong>A*</strong> is both complete and optimal (if heuristic is admissible).</p><h3>10. Real-World Applications of Problem-Solving Agents</h3><h4>10.1. GPS Navigation Systems</h4><ul><li>Finds the shortest or fastest path.</li><li>Uses A* or Dijkstra’s algorithm.</li></ul><h4>10.2. Robotics</h4><ul><li>Path planning for mobile robots.</li><li>Obstacle avoidance and goal-reaching.</li></ul><h4>10.3. Game Playing AI</h4><ul><li>Chess, Go, and video games.</li><li>Uses search trees and evaluation functions.</li></ul><h4>10.4. Automated Planning</h4><ul><li>Scheduling in manufacturing or logistics.</li><li>AI planners generate sequences of actions.</li></ul><h3>11. Key Challenges</h3><p>While problem-solving agents are powerful, they face several challenges:</p><ul><li><strong>State Explosion</strong>: In large domains, the number of states becomes unmanageable.</li><li><strong>Real-Time Constraints</strong>: Agents must act quickly in dynamic environments.</li><li><strong>Partial Observability</strong>: Limited sensor input complicates planning.</li><li><strong>Uncertainty</strong>: Agents must reason about probabilistic outcomes.</li></ul><h3>12. Extensions to Basic Problem-Solving</h3><h4>12.1. Nondeterministic Problems</h4><ul><li>Outcomes of actions are not guaranteed.</li><li>Represented using AND-OR trees.</li></ul><h4>12.2. Sensorless Problems</h4><ul><li>The agent has no sensing capability.</li><li>Must plan under uncertainty.</li></ul><h4>12.3. Contingency Planning</h4><ul><li>Plans include conditional actions.</li><li>Useful when sensing is limited or noisy.</li></ul><h4>12.4. Online Search</h4><ul><li>Agents interleave computation and action.</li><li>Useful in dynamic or unknown environments.</li></ul><h3>13. Designing Problem-Solving Agents</h3><p>Steps in designing a successful problem-solving agent:</p><ol><li><strong>Understand the Environment</strong>: Determine its type and constraints.</li><li><strong>Define Goals Clearly</strong>: Be specific and measurable.</li><li><strong>Formulate the Problem Accurately</strong>: Define states, actions, goal test, and cost.</li><li><strong>Choose the Right Search Algorithm</strong>: Based on the problem type and environment.</li><li><strong>Implement Efficiently</strong>: Optimize data structures and evaluation functions.</li><li><strong>Handle Uncertainty</strong>: Use probabilistic or adaptive methods if necessary.</li></ol><h3>14. Summary</h3><p>Problem-solving agents represent one of the most important and foundational concepts in Artificial Intelligence. Unlike reactive agents that respond to immediate stimuli, problem-solving agents look ahead, formulate goals, and search for sequences of actions that can help achieve those goals effectively and efficiently.</p><p>With well-defined components like initial states, goal tests, actions, and cost measures, these agents use search algorithms — both uninformed and informed — to explore potential solutions. From simple puzzles to complex robotics and autonomous systems, problem-solving agents provide the logical and strategic backbone that drives decision-making in intelligent systems.</p><p>As AI continues to evolve, these agents are also being extended to operate in uncertain, partially observable, and dynamic environments, making them not only smarter but also more adaptable to the real-world complexity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7ef414ce79a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Environment Types and Types of Agents]]></title>
            <link>https://medium.com/@ai.mlresearcher/environment-types-and-types-of-agents-d8bdd9286115?source=rss-a9253868464d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8bdd9286115</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Syed Hamed Raza]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 10:40:54 GMT</pubDate>
            <atom:updated>2025-03-23T10:40:54.589Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Comprehensive Study in Artificial Intelligence</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N8PoZY2x6tX5ScwL" /><figcaption>Photo by <a href="https://unsplash.com/@hauntedeyes?utm_source=medium&amp;utm_medium=referral">Lukas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Introduction</h3><p>Artificial Intelligence (AI) is a branch of computer science focused on building machines and systems that simulate human intelligence. Central to this field is the concept of <em>agents</em> — autonomous entities capable of perceiving their surroundings and acting upon them to achieve specific goals. However, an agent cannot function effectively without a deep understanding of the <strong>environment</strong> it operates within.</p><p>This article delves into two of the most foundational aspects of AI:</p><ul><li>The <strong>types of environments</strong> where agents operate.</li><li>The <strong>types of agents</strong> designed to interact with those environments.</li></ul><p>Both dimensions must be carefully considered during the design and deployment of AI systems, as they significantly influence an agent’s architecture, behavior, and performance.</p><h3>2. Understanding the AI Agent</h3><p>Before discussing types, it is essential to revisit what we mean by an agent.</p><blockquote><strong><em>Definition:</em></strong><em> An agent is anything that perceives its environment through sensors and acts upon that environment through actuators.</em></blockquote><p>A physical robot, a chatbot, a trading bot, or a self-driving car — all are examples of agents.</p><p>Agents are described using the <strong>agent function</strong>, which maps percept sequences to actions. This function is implemented via an <strong>agent program</strong>, running within some form of <strong>agent architecture</strong>.</p><p>But what makes an agent intelligent? That depends largely on the design of the agent and its compatibility with its operating environment.</p><h3>3. Types of Environments</h3><p>In AI, an environment refers to everything the agent interacts with. Understanding the <strong>nature</strong> of the environment is crucial in designing effective agents.</p><p>Russell and Norvig outline several <strong>key properties</strong> used to classify environments:</p><h4>3.1. Observable vs. Partially Observable</h4><p><strong>Fully Observable:</strong> The agent’s sensors have access to the complete state of the environment at each point in time.</p><ul><li><em>Example:</em> A chess game — the board and all pieces are visible.</li></ul><p><strong>Partially Observable:</strong> The agent has limited access to the full state due to noisy or limited sensors.</p><ul><li><em>Example:</em> A robot navigating through a dark room using sonar.</li></ul><p><strong>Importance:</strong> Fully observable environments allow for simpler agent design, while partially observable environments require memory, inference, or probabilistic reasoning.</p><h4>3.2. Deterministic vs. Stochastic</h4><p><strong>Deterministic:</strong> The next state of the environment is completely determined by the current state and the agent’s action.</p><ul><li><em>Example:</em> Solving a mathematical equation.</li></ul><p><strong>Stochastic:</strong> The outcome may involve randomness or uncertainty.</p><ul><li><em>Example:</em> Weather prediction or financial markets.</li></ul><p><strong>Importance:</strong> Deterministic environments are easier to model and predict, whereas stochastic environments demand robust decision-making strategies.</p><h4>3.3. Episodic vs. Sequential</h4><p><strong>Episodic:</strong> The agent’s experience is divided into atomic episodes. Each episode consists of a percept and an action, and is independent of others.</p><ul><li><em>Example:</em> Image classification where each image is processed independently.</li></ul><p><strong>Sequential:</strong> The current decision affects future decisions. Tasks are interdependent.</p><ul><li><em>Example:</em> Chess or autonomous driving.</li></ul><p><strong>Importance:</strong> Sequential environments require strategic planning and often involve learning from past experiences.</p><h4>3.4. Static vs. Dynamic</h4><p><strong>Static:</strong> The environment does not change while the agent is deliberating.</p><ul><li><em>Example:</em> Crossword puzzle.</li></ul><p><strong>Dynamic:</strong> The environment can change during decision-making.</p><ul><li><em>Example:</em> A robotic vacuum cleaning while people walk around.</li></ul><p><strong>Importance:</strong> Dynamic environments require real-time processing and adaptability.</p><h4>3.5. Discrete vs. Continuous</h4><p><strong>Discrete:</strong> The environment has a finite number of distinct states, percepts, and actions.</p><ul><li><em>Example:</em> Board games.</li></ul><p><strong>Continuous:</strong> The environment can be described with real-valued variables.</p><ul><li><em>Example:</em> Robotic arm movement, self-driving vehicles.</li></ul><p><strong>Importance:</strong> Continuous environments typically involve complex mathematical models and sensor processing.</p><h4>3.6. Single Agent vs. Multi-Agent</h4><p><strong>Single Agent:</strong> The agent is the only entity acting in the environment.</p><ul><li><em>Example:</em> Solving a maze.</li></ul><p><strong>Multi-Agent:</strong> Multiple agents exist, possibly with competing or cooperating goals.</p><ul><li><em>Example:</em> Multiplayer video games or stock trading.</li></ul><p><strong>Importance:</strong> In multi-agent environments, agents must account for the behavior and strategies of others.</p><h4>3.7. Known vs. Unknown Environment</h4><p><strong>Known:</strong> The agent knows the laws of the environment and outcomes of actions.</p><ul><li><em>Example:</em> A simulation with well-defined rules.</li></ul><p><strong>Unknown:</strong> The agent must learn or infer how the environment works.</p><ul><li><em>Example:</em> An intelligent system exploring a new game.</li></ul><p><strong>Importance:</strong> Known environments allow for planning, whereas unknown environments emphasize learning and adaptation.</p><h3>4. Environment Combinations</h3><p>These characteristics are not mutually exclusive. Real-world environments usually exhibit a combination of properties.</p><p><strong>Example: Autonomous Car</strong></p><ul><li>Partially Observable (limited sensor input)</li><li>Stochastic (pedestrians, weather)</li><li>Sequential (past actions affect future states)</li><li>Dynamic (traffic changes)</li><li>Continuous (steering, acceleration)</li><li>Multi-agent (other drivers, pedestrians)</li><li>Unknown (road incidents)</li></ul><p>Designing agents for such environments requires integrating sensing, planning, decision-making, and learning components.</p><h3>5. The PEAS Framework</h3><p>To describe and design intelligent agents, the <strong>PEAS framework</strong> is commonly used:</p><ul><li><strong>P</strong>erformance Measure</li><li><strong>E</strong>nvironment</li><li><strong>A</strong>ctuators</li><li><strong>S</strong>ensors</li></ul><p>This model provides a structured way to analyze an agent’s task environment.</p><h4>Example: Medical Diagnosis System</h4><ul><li><strong>Performance</strong>: Accuracy, speed, patient safety.</li><li><strong>Environment</strong>: Patient data, clinical rules, historical cases.</li><li><strong>Actuators</strong>: Diagnosis report, recommendation.</li><li><strong>Sensors</strong>: Patient input, medical history, test results.</li></ul><h3>6. Types of Agents</h3><p>The type of environment largely determines the type of agent that should be deployed. AI agents range from simple rule-based systems to sophisticated learning agents.</p><h4>6.1. Simple Reflex Agents</h4><p>These agents operate using a <strong>condition-action rule</strong>:</p><blockquote><strong><em>If (condition) then (action)</em></strong></blockquote><p>They respond to immediate percepts and do not maintain any internal state.</p><p><strong>Example:</strong></p><ul><li>A thermostat: If temperature &lt; 20°C → turn heater on.</li></ul><p><strong>Advantages:</strong></p><ul><li>Fast and efficient for simple tasks.</li><li>Easy to implement.</li></ul><p><strong>Limitations:</strong></p><ul><li>Cannot handle partial observability.</li><li>Cannot learn or plan.</li><li>Ineffective in dynamic or complex environments.</li></ul><h4>6.2. Model-Based Reflex Agents</h4><p>These agents maintain an <strong>internal model</strong> of the environment to track unobservable parts.</p><p><strong>How It Works:</strong></p><ul><li>The model updates the internal state based on actions and percepts.</li><li>Decisions are made using the updated internal state.</li></ul><p><strong>Example:</strong></p><ul><li>A robotic vacuum remembering which areas have already been cleaned.</li></ul><p><strong>Advantages:</strong></p><ul><li>Can handle partially observable environments.</li><li>Retains state and can plan short-term.</li></ul><p><strong>Limitations:</strong></p><ul><li>More complex to implement.</li><li>Requires accurate modeling.</li></ul><h4>6.3. Goal-Based Agents</h4><p>These agents act to achieve <strong>explicit goals</strong>.</p><p><strong>How It Works:</strong></p><ul><li>Evaluate future states against desired goals.</li><li>Use search and planning to select actions.</li></ul><p><strong>Example:</strong></p><ul><li>A path-finding robot that plans the shortest path to a goal.</li></ul><p><strong>Advantages:</strong></p><ul><li>More flexible and adaptable.</li><li>Can make decisions based on outcomes.</li></ul><p><strong>Limitations:</strong></p><ul><li>Computationally intensive.</li><li>Requires goal formulation and planning algorithms.</li></ul><h4>6.4. Utility-Based Agents</h4><p>These agents not only aim to achieve goals but also <strong>maximize utility</strong>, i.e., the degree of satisfaction or value associated with a state.</p><p><strong>How It Works:</strong></p><ul><li>Multiple goals are evaluated using a utility function.</li><li>Choose actions with the highest expected utility.</li></ul><p><strong>Example:</strong></p><ul><li>An AI system that selects the safest and fastest route with minimal fuel usage.</li></ul><p><strong>Advantages:</strong></p><ul><li>Can handle trade-offs and uncertainty.</li><li>Provides a richer decision-making model.</li></ul><p><strong>Limitations:</strong></p><ul><li>Defining a good utility function can be difficult.</li><li>Requires probabilistic reasoning and modeling.</li></ul><h4>6.5. Learning Agents</h4><p>These agents improve their performance over time by <strong>learning</strong> from experience.</p><p><strong>Architecture:</strong></p><ul><li><strong>Learning Element:</strong> Improves agent’s performance based on feedback.</li><li><strong>Performance Element:</strong> Chooses external actions.</li><li><strong>Critic:</strong> Gives feedback on performance.</li><li><strong>Problem Generator:</strong> Suggests new exploratory actions.</li></ul><p><strong>Example:</strong></p><ul><li>A recommendation system improving suggestions based on user feedback.</li></ul><p><strong>Advantages:</strong></p><ul><li>Highly adaptive and capable of improving in unknown environments.</li><li>Suitable for dynamic and evolving environments.</li></ul><p><strong>Limitations:</strong></p><ul><li>May need large data and time to learn.</li><li>Risk of learning incorrect behavior.</li></ul><h3>7. Comparison Table: Agent Types</h3><pre>+-------------------+--------+----------+----------+---------------------------+<br>| Agent Type        | Memory | Planning | Learning | Environment Suitability   |<br>+-------------------+--------+----------+----------+---------------------------+<br>| Simple Reflex     | ✖️     | ✖️       | ✖️       | Fully observable, static  |<br>| Model-Based Reflex| ✔️     | ✖️       | ✖️       | Partially observable       |<br>| Goal-Based        | ✔️     | ✔️       | ✖️       | Sequential, dynamic        |<br>| Utility-Based     | ✔️     | ✔️       | ✖️       | Stochastic, uncertain      |<br>| Learning Agent    | ✔️     | ✔️       | ✔️       | Unknown, evolving          |<br>+-------------------+--------+----------+----------+---------------------------+</pre><h3>8. Designing the Right Agent for the Right Environment</h3><p>Choosing the right agent depends heavily on understanding the environment. Here’s how different environments align with agent types:</p><ul><li><strong>Fully Observable, Static, Simple</strong>: Simple Reflex Agent</li><li><strong>Partially Observable, Static</strong>: Model-Based Reflex Agent</li><li><strong>Sequential, Goal-Driven Tasks</strong>: Goal-Based Agent</li><li><strong>Uncertain, Trade-Off Scenarios</strong>: Utility-Based Agent</li><li><strong>Dynamic, Unknown, Complex</strong>: Learning Agent</li></ul><p><strong>Example Use Cases:</strong></p><ul><li><strong>Bank fraud detection system</strong> → Utility-Based / Learning Agent</li><li><strong>Traffic light system</strong> → Model-Based Reflex Agent</li><li><strong>Autonomous warehouse robot</strong> → Goal-Based + Learning Agent</li><li><strong>Voice-controlled assistant</strong> → Learning + Utility-Based Agent</li></ul><h3>9. Hybrid Agents</h3><p>In practice, agents often combine multiple architectures.</p><p><strong>Hybrid Agent Architecture</strong> integrates:</p><ul><li><strong>Reactive components</strong> for quick response.</li><li><strong>Deliberative components</strong> for planning.</li><li><strong>Learning components</strong> for adaptation.</li></ul><p><strong>Example: A Mars Rover</strong></p><ul><li>Reacts to immediate obstacles (reactive)</li><li>Plans its route to exploration points (deliberative)</li><li>Learns from terrain experience (learning)</li></ul><h3>10. Future Directions in Agent Research</h3><p>As AI evolves, research in agent design focuses on:</p><ul><li><strong>Collaborative multi-agent systems</strong> (e.g., swarm robotics)</li><li><strong>Emotionally aware agents</strong> (affective computing)</li><li><strong>Ethical reasoning agents</strong> (AI ethics)</li><li><strong>General-purpose agents</strong> (AGI)</li></ul><p>Advanced environments will demand agents that can reason about social behavior, morality, and even self-awareness.</p><h3>11. Conclusion</h3><p>Understanding <strong>environment types</strong> and <strong>agent types</strong> is crucial for anyone designing AI systems. The nature of the environment — whether it is deterministic or stochastic, static or dynamic — influences how an agent must perceive, reason, and act.</p><p>Different agent architectures, from simple reflexes to sophisticated learning systems, cater to different tasks and challenges. Intelligent systems in the modern world are often hybrid, blending multiple agent capabilities to meet the demands of real-world environments.</p><p>This foundation allows AI practitioners to build systems that are not only functional but also adaptive, ethical, and aligned with human goals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8bdd9286115" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agents, Intelligent Agents, Rationality, and PEAS]]></title>
            <link>https://medium.com/@ai.mlresearcher/agents-intelligent-agents-rationality-and-peas-1c2c52a49914?source=rss-a9253868464d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c2c52a49914</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Syed Hamed Raza]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 10:45:42 GMT</pubDate>
            <atom:updated>2025-03-22T10:45:42.372Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Core Building Blocks of AI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AD9sBIc8TEl1czMR" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Introduction</h3><p>Artificial Intelligence (AI) is centered on building systems that can perceive, reason, and act intelligently in a given environment. One of the most foundational concepts in the study and development of AI systems is the notion of <strong>agents</strong>. An agent can be anything that perceives its environment through sensors and acts upon that environment through actuators. From robotic vacuum cleaners to self-driving cars and intelligent chatbots, agents lie at the heart of all intelligent systems.</p><p>In this article, we delve deeply into the concepts of agents, <strong>intelligent agents</strong>, the principle of <strong>rationality</strong>, and the <strong>PEAS</strong> framework — four pillars that provide structure and direction for designing intelligent systems. These ideas are not only central to understanding AI theory but also essential for applying AI in real-world applications.</p><h3>2. What is an Agent?</h3><p>In the simplest terms, an <strong>agent</strong> is an entity that perceives its environment and takes actions to achieve specific goals. Formally, an agent is defined as:</p><blockquote><strong><em>Agent = something that perceives through sensors and acts through actuators.</em></strong></blockquote><h4>2.1. Examples of Agents</h4><ul><li>A <strong>human</strong> agent: Eyes (sensors), limbs/speech organs (actuators).</li><li>A <strong>robotic vacuum cleaner</strong>: Infrared sensors (sensors), wheels/motor (actuators).</li><li>A <strong>chess program</strong>: Input (moves from an opponent), Output (its next move).</li><li>A <strong>web crawler</strong>: Input (web pages), Output (requests to servers, storing data).</li></ul><p>Agents may be physical or virtual, simple or complex, reactive or deliberative.</p><h3>3. The Agent Function and Agent Program</h3><p>At the core of every agent is an <strong>agent function</strong>, which maps a percept sequence to an action. In other words, based on everything the agent has perceived so far, what action should it take next?</p><blockquote><strong><em>Agent Function: f: P* → A<br> (P* is the set of all possible percept sequences, and A is the set of actions.)</em></strong></blockquote><p>However, the agent function is abstract and cannot be implemented directly due to the potentially infinite number of percept sequences. Hence, AI practitioners implement an <strong>agent program</strong>, which is a concrete execution of this function, running on the agent architecture.</p><h3>4. Intelligent Agents</h3><p>Not all agents are created equal. Some simply follow a fixed rule, while others analyze, learn, adapt, and make strategic decisions. An <strong>intelligent agent</strong> is one that acts appropriately for its goals and environment, is flexible to changing conditions, and learns from experience.</p><h4>4.1 Characteristics of Intelligent Agents</h4><ul><li><strong>Autonomy</strong>: The agent operates without human intervention.</li><li><strong>Reactivity</strong>: It perceives and responds to changes in the environment.</li><li><strong>Proactiveness</strong>: It takes initiative toward achieving goals.</li><li><strong>Social Ability</strong>: Some intelligent agents can interact with other agents or humans.</li></ul><h3>5. Rationality in Agents</h3><p>A key attribute of intelligent agents is <strong>rationality</strong>. Rationality refers to the ability of an agent to make the “right” decision based on the information it has.</p><h4>5.1. What is a Rational Agent?</h4><p>A <strong>rational agent</strong> is one that does the right thing — that is, the action that maximizes the expected value of the performance measure, given the percept sequence and built-in knowledge.</p><h4>5.2. Rational ≠ Omniscient</h4><p>It is important to differentiate rationality from omniscience. A rational agent is not expected to always succeed but to make the best possible decision based on what it knows.</p><blockquote><strong><em>For example, a self-driving car that chooses the safest and shortest route based on real-time traffic data is rational. It might still get stuck in a traffic jam due to unpredictable events, but it made the best possible choice at the time.</em></strong></blockquote><h4>5.3. Factors Affecting Rationality</h4><ul><li><strong>Performance Measure</strong>: A criterion that evaluates how well the agent is doing.</li><li><strong>Percept History</strong>: The complete history of what the agent has perceived.</li><li><strong>Knowledge</strong>: What the agent knows about the environment and itself.</li><li><strong>Actions Available</strong>: What actions it can take in its current state.</li></ul><h3>6. PEAS Framework</h3><p>When designing intelligent agents, especially for complex systems, AI engineers use the <strong>PEAS</strong> framework. It stands for:</p><ul><li><strong>P</strong>: Performance measure</li><li><strong>E</strong>: Environment</li><li><strong>A</strong>: Actuators</li><li><strong>S</strong>: Sensors</li></ul><p>This model helps define the task environment of an agent clearly.</p><h3>6.1. Components of PEAS</h3><h4><strong>Performance Measure</strong></h4><p>This quantifies the success of the agent’s behavior. Examples:</p><ul><li>For a delivery robot: timely deliveries, energy efficiency.</li><li>For a trading bot: return on investment, minimal risk exposure.</li></ul><h4>Environment</h4><p>This includes everything the agent interacts with.</p><ul><li>For a vacuum robot: the floor layout, furniture, dust.</li><li>For a chatbot: user queries, text input/output, tone.</li></ul><h4>Actuators</h4><p>These are the parts of the agent that take actions.</p><ul><li>For a drone: propellers, camera, delivery arm.</li><li>For a software agent: API calls, messages, data output.</li></ul><h4>Sensors</h4><p>These allow the agent to perceive its environment.</p><ul><li>For a car: cameras, radar, GPS.</li><li>For a weather bot: temperature sensors, satellite feeds.</li></ul><h3>7. Types of Environments</h3><p>Understanding the nature of the environment is critical to designing the right agent. Environments can be categorized using the following characteristics</p><pre>+-------------------------------+--------------------------------------------------------------+<br>| Environment Property          | Description                                                  |<br>+-------------------------------+--------------------------------------------------------------+<br>| Observable vs Partially Obs. | Can the agent fully see the state of the environment?         |<br>| Deterministic vs Stochastic  | Is the next state predictable based on the current action?    |<br>| Episodic vs Sequential        | Are episodes independent, or do actions depend on previous?  |<br>| Static vs Dynamic             | Does the environment change while the agent is thinking?     |<br>| Discrete vs Continuous        | Is the number of possible states/actions finite or infinite? |<br>| Single-agent vs Multi-agent   | Is the agent acting alone, or are other agents involved?     |<br>+-------------------------------+--------------------------------------------------------------+</pre><h4><strong>Example: Self-Driving Car</strong></h4><ul><li>Partially Observable (not all traffic details are known)</li><li>Stochastic (other drivers’ actions may be unpredictable)</li><li>Sequential (decisions depend on past states)</li><li>Dynamic (real-time changes)</li><li>Continuous (many variables and control parameters)</li><li>Multi-agent (interacts with other drivers)</li></ul><h3>8. Types of Agents</h3><p>Agents can be categorized by increasing levels of intelligence and capabilities:</p><h4>8.1. Simple Reflex Agents</h4><p>These respond to the current percept only.</p><ul><li>Use <strong>condition-action rules</strong> (if-then).</li><li>E.g., a thermostat turning on the heater if temperature &lt; 20°C.</li></ul><p><strong>Limitation</strong>: Cannot handle partial observability or long-term goals.</p><h4>8.2. Model-Based Reflex Agents</h4><p>They maintain some <strong>internal state</strong> of the environment to handle partial observability.</p><ul><li>E.g., a vacuum robot remembering which rooms it has already cleaned.</li></ul><h4>8.3. Goal-Based Agents</h4><p>These agents choose actions based on <strong>goal states</strong>.</p><ul><li>Search and planning are used to find sequences of actions.</li><li>E.g., a GPS navigator finding the shortest path to a destination.</li></ul><h4>8.4. Utility-Based Agents</h4><p>Not all goal states are equally desirable. Utility-based agents measure <strong>how good</strong> a state is.</p><ul><li>They maximize expected utility.</li><li>E.g., choosing a slightly longer but safer route to avoid traffic jams.</li></ul><h4>8.5. Learning Agents</h4><p>These agents can <strong>learn from experience</strong> and improve performance over time.</p><ul><li>Components:</li><li>Learning element</li><li>Critic (provides feedback)</li><li>Performance element (actual behavior)</li><li>Problem generator (explores new actions)</li></ul><p><strong>Example</strong>: A robot that learns to walk more efficiently over time.</p><h3>9. Designing Intelligent Agents</h3><p>Designing an intelligent agent involves several critical steps:</p><h4>9.1. Define the Problem and Task</h4><ul><li>What is the agent’s goal?</li><li>What are its success criteria (performance measures)?</li></ul><h4>9.2. Understand the Environment</h4><ul><li>Is it fully observable or partially?</li><li>Is it static or dynamic?</li></ul><h4>9.3. Specify the Agent Type</h4><ul><li>Will it be a simple reflex agent or a learning agent?</li></ul><h4>9.4. Design the Agent Architecture</h4><ul><li>How will it store knowledge?</li><li>What algorithms will it use for decision-making?</li></ul><h4>9.5. Implement PEAS Description</h4><ul><li>Clearly outline sensors, actuators, environment, and performance measures.</li></ul><h3>10. Real-World Applications of Agents</h3><h4>10.1. Autonomous Vehicles</h4><ul><li><strong>Sensors</strong>: Cameras, radar, GPS</li><li><strong>Actuators</strong>: Wheels, brakes, steering</li><li><strong>Environment</strong>: Roads, traffic signals, pedestrians</li><li><strong>Performance</strong>: Safety, fuel efficiency, travel time</li></ul><h4>10.2. Smart Assistants (e.g., Siri, Alexa)</h4><ul><li><strong>Sensors</strong>: Microphone (voice input)</li><li><strong>Actuators</strong>: Speaker (audio output), screen</li><li><strong>Environment</strong>: User context, online services</li><li><strong>Performance</strong>: Accuracy of answers, speed, user satisfaction</li></ul><h4>10.3. Industrial Robots</h4><ul><li><strong>Sensors</strong>: Cameras, proximity detectors</li><li><strong>Actuators</strong>: Robotic arms, conveyor belts</li><li><strong>Environment</strong>: Assembly lines</li><li><strong>Performance</strong>: Production speed, error rate, safety</li></ul><h3>11. Ethical Considerations in Agent Design</h3><p>As agents become more autonomous and powerful, ethical concerns must be addressed:</p><ul><li><strong>Bias and Fairness</strong>: Ensuring that agents do not learn or apply discriminatory patterns.</li><li><strong>Accountability</strong>: Determining who is responsible for the agent’s actions.</li><li><strong>Privacy</strong>: Ensuring sensitive data is not misused.</li><li><strong>Safety</strong>: Preventing agents from making harmful decisions.</li></ul><h3>12. Summary and Conclusion</h3><p>The study of <strong>agents</strong> is foundational to understanding and building intelligent systems. From simple reflex agents that react to basic conditions to complex learning agents that adapt and optimize over time, the design of agents reflects the depth and power of artificial intelligence.</p><p>The PEAS framework offers a structured approach to task environment design, ensuring that developers think through all necessary components. <strong>Rationality</strong> provides the principle that guides agent behavior, helping them make optimal decisions given their knowledge and percept history.</p><p>Whether in robotics, software applications, or intelligent decision-making systems, agents continue to drive the progress of AI. Understanding these concepts not only clarifies how intelligent systems function but also empowers the next generation of researchers and developers to build smarter, safer, and more ethical AI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c2c52a49914" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Foundations of Artificial Intelligence]]></title>
            <link>https://medium.com/@ai.mlresearcher/foundations-of-artificial-intelligence-cd8440e37a6f?source=rss-a9253868464d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd8440e37a6f</guid>
            <category><![CDATA[ai-artificial-inteligence]]></category>
            <category><![CDATA[application-of-ai]]></category>
            <dc:creator><![CDATA[Syed Hamed Raza]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 10:40:10 GMT</pubDate>
            <atom:updated>2025-03-22T10:40:10.428Z</atom:updated>
            <content:encoded><![CDATA[<h4>Applications and History</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fz_5ASL-r9L-fc5W" /><figcaption>Photo by <a href="https://unsplash.com/@siderius_creativ?utm_source=medium&amp;utm_medium=referral">Gerard Siderius</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Artificial Intelligence (AI) is no longer a futuristic concept confined to the realms of science fiction; it is a transformative force shaping industries, economies, and the very fabric of human life. From smart assistants that respond to our voice commands to algorithms that drive autonomous vehicles, AI is revolutionizing how we interact with technology. This article presents a comprehensive overview of the foundations of AI, its diverse applications, and the historical journey that has shaped its development. The aim is to provide a 360-degree understanding of AI as it stands today, how it evolved, and where it might be headed.</p><h3>1. What is Artificial Intelligence?</h3><p>AI is the branch of computer science concerned with building smart machines capable of performing tasks that typically require human intelligence. These tasks include reasoning, learning, problem-solving, perception, language understanding, and even creativity. AI can be categorized broadly into two types:</p><ol><li><strong>Narrow AI</strong>: Systems designed to handle a specific task (e.g., voice recognition, recommendation engines).</li><li><strong>General AI</strong>: Hypothetical systems that possess the ability to understand, learn, and apply knowledge across a wide range of tasks, mimicking human intelligence in a holistic manner.</li></ol><h3>2. Foundational Concepts of AI</h3><h4>2.1 Philosophy and Cognitive Science</h4><p>AI owes much of its foundation to ancient philosophical inquiries about the mind and reasoning. Questions posed by philosophers like Plato and Aristotle about the nature of knowledge, learning, and logic laid the groundwork for AI’s theoretical frameworks. Cognitive science added to this by offering insights into how human beings think, learn, and remember.</p><h4>2.2 Mathematics and Logic</h4><p>Mathematics forms the bedrock of AI. Boolean algebra, probability theory, statistics, and calculus are integral in building algorithms that can predict outcomes, make decisions, and learn from data. Logic, especially propositional and predicate logic, is central to rule-based systems and automated reasoning.</p><h4>2.3 Computer Science</h4><p>The actual realization of AI concepts is made possible through computer science. Algorithms, data structures, databases, programming languages, and computational theory collectively enable the implementation and deployment of AI systems.</p><h4>2.4 Neuroscience</h4><p>Understanding how the human brain functions has greatly influenced AI development. Artificial Neural Networks (ANNs), which mimic the structure and functioning of biological neurons, are the basis of deep learning and modern AI.</p><h4>2.5 Linguistics</h4><p>Natural Language Processing (NLP), a vital area of AI, relies on linguistic principles to allow machines to understand, interpret, and respond to human language.</p><h3>3. Historical Milestones in AI</h3><h4>3.1 Antiquity to 19th Century</h4><p>The idea of intelligent machines is ancient. Greek myths spoke of mechanical servants. In the Middle Ages, automatons were designed for entertainment. However, these were mechanical and lacked true intelligence.</p><h4>3.2 Early 20th Century: Theoretical Foundations</h4><ul><li><strong>Alan Turing</strong>: In 1936, Turing introduced the concept of a “universal machine” that could simulate any computation process. In 1950, he proposed the Turing Test to assess a machine’s ability to exhibit human-like intelligence.</li><li><strong>Norbert Wiener</strong>: Laid the foundation for cybernetics, the study of control and communication in animals and machines.</li></ul><h4>3.3 1956 — The Birth of AI</h4><p>The Dartmouth Conference, organized by John McCarthy, Marvin Minsky, Nathaniel Rochester, and Claude Shannon, marked the official birth of AI as a field. The term “Artificial Intelligence” was coined here. Early efforts focused on symbolic AI — using rules and logic to simulate intelligent behavior.</p><h4>3.4 1960s–70s: The Rise and Fall</h4><p>Early successes included programs like ELIZA (a rudimentary chatbot) and SHRDLU (which could manipulate virtual objects). However, limitations in computing power and overly optimistic expectations led to the first “AI winter,” a period of reduced funding and interest.</p><h4>3.5 1980s: Expert Systems</h4><p>AI saw a resurgence with the development of expert systems like MYCIN, which could diagnose bacterial infections. These systems relied on hand-coded rules, making them brittle and hard to scale.</p><h4>3.6 1990s: Machine Learning Emerges</h4><p>The focus shifted from rule-based systems to data-driven models. Machine Learning (ML) allowed systems to learn from data. In 1997, IBM’s Deep Blue defeated world chess champion Garry Kasparov — a landmark achievement.</p><h4>3.7 2000s–Present: The Age of Big Data and Deep Learning</h4><p>The explosion of digital data and advances in computational power, especially GPUs, led to breakthroughs in deep learning. Notable milestones include:</p><ul><li><strong>ImageNet Challenge</strong>: Deep learning models surpassed human-level accuracy in object recognition.</li><li><strong>AlphaGo</strong>: Developed by DeepMind, it defeated the world champion Go player.</li><li><strong>ChatGPT</strong>: Demonstrated capabilities in language understanding and generation.</li></ul><h3>4. Applications of Artificial Intelligence</h3><p>AI is a general-purpose technology with applications spanning almost every domain</p><h4>4.1 Healthcare</h4><ul><li><strong>Diagnosis</strong>: AI algorithms detect diseases from X-rays, MRIs, and pathology slides.</li><li><strong>Drug Discovery</strong>: Accelerates the process of finding potential drug candidates.</li><li><strong>Personalized Medicine</strong>: AI tailors treatment plans based on genetic information.</li></ul><h4>4.2 Finance</h4><ul><li><strong>Fraud Detection</strong>: Identifies unusual patterns and transactions.</li><li><strong>Algorithmic Trading</strong>: Executes trades at optimal times using predictive models.</li><li><strong>Credit Scoring</strong>: Assesses creditworthiness with greater accuracy.</li></ul><h4>4.3 Transportation</h4><ul><li><strong>Autonomous Vehicles</strong>: Self-driving cars use AI for perception, decision-making, and navigation.</li><li><strong>Traffic Management</strong>: Predictive algorithms optimize traffic flow in real-time.</li></ul><h4>4.4 Education</h4><ul><li><strong>Personalized Learning</strong>: Adapts content to a learner’s pace and style.</li><li><strong>Automated Grading</strong>: Assists educators in assessing large volumes of assignments.</li></ul><h4>4.5 Manufacturing</h4><ul><li><strong>Predictive Maintenance</strong>: Identifies equipment failures before they occur.</li><li><strong>Quality Control</strong>: Detects defects in products during production.</li></ul><h4>4.6 Agriculture</h4><ul><li><strong>Precision Farming</strong>: Uses AI to analyze soil health, weather patterns, and crop status.</li><li><strong>Yield Prediction</strong>: Helps in planning and logistics.</li></ul><h4>4.7 Customer Service</h4><ul><li><strong>Chatbots</strong>: Provide 24/7 support.</li><li><strong>Sentiment Analysis</strong>: Gauges customer satisfaction and guides service improvement.</li></ul><h4>4.8 Entertainment</h4><ul><li><strong>Recommendation Systems</strong>: Suggest movies, music, and content.</li><li><strong>Game AI</strong>: Powers intelligent behavior in video game characters.</li></ul><h4>4.9 Law and Order</h4><ul><li><strong>Predictive Policing</strong>: Forecasts crime hotspots.</li><li><strong>Legal Research</strong>: AI aids in quickly sifting through large volumes of legal texts.</li></ul><h4>4.10 Environmental Monitoring</h4><ul><li><strong>Climate Modeling</strong>: Predicts climate change patterns.</li><li><strong>Wildlife Tracking</strong>: Uses computer vision to monitor endangered species.</li></ul><h3>5. Challenges and Ethical Considerations</h3><h4>5.1 Bias and Fairness</h4><p>AI systems can inherit and amplify human biases. Ensuring fairness and transparency is a major challenge.</p><h4>5.2 Privacy</h4><p>With AI’s capability to analyze personal data, safeguarding user privacy is critical.</p><h4>5.3 Job Displacement</h4><p>Automation could render many jobs obsolete. However, it may also create new opportunities.</p><h4>5.4 Security</h4><p>AI can be weaponized. Deepfakes and autonomous drones pose new threats.</p><h4>5.5 Explainability</h4><p>Many AI models, especially deep learning systems, operate as “black boxes,” making their decision processes difficult to interpret.</p><h3>6. The Future of AI</h3><p>The trajectory of AI suggests that its impact will only grow. Promising areas include:</p><ul><li><strong>Artificial General Intelligence (AGI)</strong>: Systems with broad cognitive abilities.</li><li><strong>AI in Space Exploration</strong>: Autonomous rovers and predictive modeling for missions.</li><li><strong>AI and Creativity</strong>: Generating music, art, and literature.</li><li><strong>Brain-Computer Interfaces</strong>: Direct communication between brains and machines.</li></ul><h3>Conclusion</h3><p>AI is not just a technological trend; it is a paradigm shift. Its foundations are deeply rooted in multiple disciplines, its history marked by bursts of progress and setbacks, and its applications are already transforming the world. As we stand on the cusp of even greater advancements, the responsible development and deployment of AI will determine whether it serves as a boon or a challenge for humanity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd8440e37a6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to the Artificial Intelligence Course]]></title>
            <link>https://medium.com/@ai.mlresearcher/introduction-to-the-artificial-intelligence-course-32941fa665f0?source=rss-a9253868464d------2</link>
            <guid isPermaLink="false">https://medium.com/p/32941fa665f0</guid>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Syed Hamed Raza]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 10:27:12 GMT</pubDate>
            <atom:updated>2025-03-22T10:27:12.835Z</atom:updated>
            <content:encoded><![CDATA[<h4>From Problem-Solving to Machine Learning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*46Zny30KJw3jBCuF" /><figcaption>Photo by <a href="https://unsplash.com/@neeqolah?utm_source=medium&amp;utm_medium=referral">Neeqolah Creative Works</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Overview of the Course</h3><p>Artificial Intelligence (AI) has revolutionized the way we perceive technology. From intelligent personal assistants to self-driving cars, AI has woven itself into the fabric of modern life. The course “Artificial Intelligence” is a comprehensive journey through the foundational and advanced concepts that define the field today. This course introduces students to the principles, methodologies, tools, and applications of AI, grounded in the classic and widely recognized textbook <em>“Artificial Intelligence: A Modern Approach”</em> by Stuart Russell and Peter Norvig.</p><p>Designed for students of computer science and related disciplines, this course offers a deep dive into problem-solving, intelligent agents, search algorithms, game theory, logical reasoning, machine learning, and more. It is structured to build both theoretical understanding and practical insights into how AI works and how it is applied in the real world.</p><h3>2. Foundations of AI: History, Scope, and Applications</h3><p>The journey begins with an introduction to the foundations of AI. Students explore the definitions of AI and the philosophical and scientific questions it raises. AI can be broadly understood in four approaches: systems that think like humans, act like humans, think rationally, and act rationally. The course emphasizes the latter two — rational agents — which form the basis of modern AI systems.</p><p>A historical perspective helps students appreciate the milestones in AI’s evolution — from Turing’s foundational work to the emergence of machine learning and deep learning in recent decades. Real-world applications in healthcare, finance, robotics, and natural language processing highlight the relevance of AI today and its potential for the future.</p><h3>3. Intelligent Agents and Rational Behavior</h3><p>Chapter 2 of the textbook introduces the concept of agents — entities that perceive their environment through sensors and act upon it using actuators. The course delves into the architecture of intelligent agents and explores how rationality guides their decisions. Students learn how an agent’s behavior can be evaluated in terms of performance measures and how the agent-environment interaction plays a crucial role.</p><p>The PEAS (Performance measure, Environment, Actuators, and Sensors) framework is introduced as a way to formally specify task environments. The classification of environments (fully/partially observable, deterministic/stochastic, static/dynamic, discrete/continuous) and agents (simple reflex, model-based, goal-based, utility-based) helps students design appropriate AI solutions.</p><h3>4. Problem-Solving Agents and Classical Problems</h3><p>In Chapter 3, the focus shifts to problem-solving agents. These agents work in deterministic, fully observable environments where the solution is a sequence of actions. The Vacuum Cleaner World serves as a classic introductory example, helping students understand how an agent can be programmed to maximize performance.</p><p>Students explore well-known problems such as the 8-puzzle and 8-queen problems. These help illustrate how a problem is formulated with an initial state, actions, transition model, goal test, and path cost. Through tree search strategies, students begin to develop skills in modeling and solving problems effectively.</p><h3>5. Uninformed Search Strategies</h3><p>Search algorithms are central to AI. The course introduces uninformed search strategies that do not have any domain-specific knowledge. Breadth-First Search (BFS), Uniform Cost Search (UCS), Depth-First Search (DFS), Depth-Limited Search (DLS), and Iterative Deepening Search (IDS) are studied in detail.</p><p>Students learn to evaluate algorithms based on criteria like completeness, optimality, time complexity, and space complexity. For example, BFS is complete and optimal (for uniform step cost), but its space complexity is high. IDS combines the benefits of DFS’s space efficiency and BFS’s completeness, making it a preferred choice in many scenarios.</p><h3>6. Informed Search and Heuristics</h3><p>To improve efficiency, informed (heuristic) search strategies are introduced. These use domain-specific knowledge to estimate the cost of reaching the goal. Greedy Best-First Search and A* search are two key algorithms discussed.</p><p>A* is particularly important because it combines path cost and heuristic information. Students explore the properties of A*, such as admissibility (heuristics never overestimate the cost) and consistency (monotonicity). Dominance among heuristics helps students design better strategies for search problems.</p><h3>7. Local Search and Optimization</h3><p>Not all problems require path solutions. Some need only the final state — such as in optimization problems. Local search algorithms, including Hill Climbing, Simulated Annealing, and Beam Search, are explored in this context.</p><p>These algorithms are particularly effective in large or infinite state spaces where traditional search methods are impractical. Hill climbing focuses on moving towards higher value states, while simulated annealing introduces randomness to escape local optima. Genetic algorithms, inspired by biological evolution, are also introduced as robust optimization techniques.</p><h3>8. Constraint Satisfaction Problems (CSPs)</h3><p>AI often needs to solve problems by satisfying a set of constraints, such as scheduling tasks or coloring maps. Constraint Satisfaction Problems are studied in detail, including backtracking search and constraint propagation.</p><p>Students learn techniques like Minimum Remaining Values (MRV), Degree Heuristic, and Least Constraining Value (LCV), which improve search efficiency. Forward checking and the AC-3 algorithm demonstrate how to prune search spaces by enforcing arc consistency, reducing computational overhead.</p><h3>9. Adversarial Search and Game Playing</h3><p>AI in games is a fascinating domain, covered in Chapter 5. Here, students explore adversarial search techniques for two-player games such as chess and tic-tac-toe. The Minimax algorithm forms the foundation for game-playing AI.</p><p>Alpha-beta pruning enhances Minimax by eliminating branches that don’t affect the final decision, making search more efficient. Multiplayer and stochastic games are also discussed, introducing students to complex decision-making under uncertainty and resource constraints.</p><h3>10. Knowledge-Based Agents and Logic</h3><p>AI isn’t just about searching and learning — it’s also about reasoning. Logical agents form the bridge between knowledge representation and inference. Students are introduced to propositional logic and first-order logic.</p><p>The Wumpus World is a classical example used to demonstrate how agents can reason under uncertainty. Techniques like Modus Ponens and Modus Tollens are studied along with satisfiability checking, forward chaining, and backward chaining. These allow agents to deduce new knowledge from known facts.</p><h3>11. Introduction to Machine Learning</h3><p>Machine Learning (ML) marks a significant shift from rule-based AI to data-driven AI. Students are introduced to the concept of machines learning from experience, recognizing patterns, and making predictions. The course outlines the need for ML, types of learning (supervised, unsupervised, reinforcement), and key distinctions between them.</p><h3>12. Supervised Learning: Classification and Regression</h3><p>In supervised learning, the machine is trained on labeled data. The course covers classification (predicting discrete labels) and regression (predicting continuous values). Students study real-life applications such as spam detection, disease prediction, and housing price estimation.</p><p>They also learn about performance evaluation metrics like accuracy, precision, recall, and mean squared error. These concepts form the basis for designing and evaluating intelligent systems in practical scenarios.</p><h3>13. Neural Networks and Deep Learning</h3><p>Neural networks are inspired by the human brain and form the backbone of modern AI applications. Students are introduced to the architecture of neural networks — including layers, neurons, activation functions, and training processes.</p><p>Backpropagation, gradient descent, and common network structures are discussed. This module sets the stage for understanding how deep learning powers applications like image recognition, speech synthesis, and natural language understanding.</p><h3>14. Advanced Topics in AI</h3><p>The course concludes with a glimpse into advanced topics that are reshaping the future of AI. These include:</p><ul><li><strong>Natural Language Processing (NLP):</strong> AI’s ability to understand and generate human language.</li><li><strong>Computer Vision:</strong> Enabling machines to interpret visual data.</li><li><strong>Digital Image Processing:</strong> Enhancing image-based AI applications.</li></ul><p>These domains showcase the interdisciplinary nature of AI, integrating knowledge from linguistics, neuroscience, mathematics, and engineering.</p><h3>15. Course Learning Outcomes and Revision</h3><p>Throughout the course, the following Course Learning Outcomes (CLOs) are targeted:</p><ul><li><strong>CLO1:</strong> Understand the fundamental concepts, historical development, and applications of AI.</li><li><strong>CLO2:</strong> Apply problem-solving techniques, search algorithms, and decision-making strategies in AI.</li><li><strong>CLO3:</strong> Analyze constraint satisfaction problems, supervised learning methods, and develop intelligent systems.</li></ul><p>The final sessions of the course are devoted to revision, discussion, and reflection. Students consolidate their learning, engage in project work or case studies, and prepare for assessments.</p><h3>Conclusion</h3><p>This course on Artificial Intelligence offers a balanced and structured introduction to one of the most transformative technologies of our time. By combining theory with practical application, students develop the skills needed to design, implement, and evaluate intelligent systems.</p><p>Whether you’re aiming for a career in AI, machine learning, data science, or robotics — or simply curious about the future of technology — this course provides the essential foundation to begin that journey. With guidance from <em>“Artificial Intelligence: A Modern Approach”</em>, learners gain both depth and breadth in AI, empowering them to contribute meaningfully to the future of intelligent computing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32941fa665f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide to Programming Fundamentals in C++]]></title>
            <link>https://medium.com/@ai.mlresearcher/comprehensive-guide-to-programming-fundamentals-in-c-11fbe6afd9eb?source=rss-a9253868464d------2</link>
            <guid isPermaLink="false">https://medium.com/p/11fbe6afd9eb</guid>
            <category><![CDATA[c-programming-basics]]></category>
            <category><![CDATA[preprocessors]]></category>
            <category><![CDATA[control-statement-in-c]]></category>
            <category><![CDATA[loops-in-c]]></category>
            <dc:creator><![CDATA[Syed Hamed Raza]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 10:32:24 GMT</pubDate>
            <atom:updated>2025-03-17T10:32:24.319Z</atom:updated>
            <content:encoded><![CDATA[<h4>Program Construction, Control Statements, Arrays, and More</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ziSmMWJMDD33lcVl" /><figcaption>Photo by <a href="https://unsplash.com/@ffstop?utm_source=medium&amp;utm_medium=referral">Fotis Fotopoulos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Introduction to C++ Programming</h3><p>C++ is a <strong>general-purpose, object-oriented programming language</strong> that extends <strong>C</strong> by adding features such as <strong>classes, objects, and strong type checking</strong>. It is widely used for <strong>system programming, game development, and high-performance applications</strong>.</p><h4>Key Features of C++</h4><p>✔ <strong>Multi-Paradigm</strong> — Supports procedural, object-oriented, and functional programming.<br> ✔ <strong>High Performance</strong> — Offers direct memory manipulation for optimized speed.<br> ✔ <strong>Rich Library Support</strong> — Includes Standard Template Library (STL).<br> ✔ <strong>Portability</strong> — Runs across multiple operating systems.<br> ✔ <strong>Strong Typing</strong> — Ensures type safety and prevents errors.</p><h3>2. Program Construction in C++</h3><p>A <strong>C++ program</strong> consists of:</p><ol><li><strong>Preprocessor Directives</strong> (e.g., #include &lt;iostream&gt;)</li><li><strong>Main Function</strong> (int main())</li><li><strong>Statements &amp; Expressions</strong></li><li><strong>Functions &amp; Classes (Optional)</strong></li></ol><h4>Basic Structure of a C++ Program</h4><pre>#include &lt;iostream&gt; // Preprocessor directive<br>using namespace std;<br><br>int main() { // Main function<br>    cout &lt;&lt; &quot;Hello, World!&quot; &lt;&lt; endl; // Output statement<br>    return 0; // Indicates successful execution<br>}</pre><h4>Compilation and Execution Process</h4><ol><li><strong>Writing Code</strong> — Use a text editor or IDE (e.g., Code::Blocks, VS Code).</li><li><strong>Compiling</strong> — Converts the code into machine language using g++ filename.cpp -o output.exe.</li><li><strong>Executing</strong> — Runs the compiled program using ./output.exe.</li></ol><h3>3. Input and Output (I/O) Statements in C++</h3><p>I/O operations are essential for <strong>interacting with users and processing data</strong>.</p><h4>Standard Output (cout)</h4><p>Used to print data on the console.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>int main() {<br>    cout &lt;&lt; &quot;Welcome to C++!&quot; &lt;&lt; endl;<br>    return 0;<br>}</pre><p>✔ &lt;&lt; is the <strong>insertion operator</strong>.<br> ✔ endl moves the cursor to the next line.</p><h4>Standard Input (cin)</h4><p>Used to <strong>take input</strong> from the user.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>int main() {<br>    int age;<br>    cout &lt;&lt; &quot;Enter your age: &quot;;<br>    cin &gt;&gt; age;<br>    cout &lt;&lt; &quot;You are &quot; &lt;&lt; age &lt;&lt; &quot; years old.&quot; &lt;&lt; endl;<br>    return 0;<br>}</pre><p>✔ &gt;&gt; is the <strong>extraction operator</strong>.<br> ✔ cin reads input and stores it in a variable.</p><h4>getline() for String Input</h4><p>Used to read a <strong>full line</strong> including spaces.</p><pre>string name;<br>cout &lt;&lt; &quot;Enter your name: &quot;;<br>getline(cin, name);</pre><h3>4. Preprocessor Directives in C++</h3><p>Preprocessor directives <strong>begin with </strong><strong>#</strong> and are processed before compilation.</p><h4>Common Preprocessor Directives</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*78MpQ0UIrKR_lUr0TVLuug.png" /></figure><p><strong>Example: Macros Using </strong><strong>#define</strong></p><pre>#include &lt;iostream&gt;<br>#define PI 3.14159<br><br>int main() {<br>    cout &lt;&lt; &quot;Value of PI: &quot; &lt;&lt; PI &lt;&lt; endl;<br>    return 0;<br>}</pre><h3>5. Data Types in C++ (Revised)</h3><p>C++ supports <strong>various data types</strong> for storing different kinds of values.</p><h4>Primitive Data Types</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*2ASSGnRBX2_KmI1BshT7aw.png" /></figure><h3>Derived Data Types</h3><p>✔ <strong>Arrays</strong> — Collection of elements of the same type.<br> ✔ <strong>Pointers</strong> — Stores memory addresses.<br> ✔ <strong>Structures &amp; Classes</strong> — Custom data types.</p><h3>6. Control and Iterative Statements in C++</h3><p>Control statements <strong>direct the flow of execution</strong> based on conditions.</p><h4>6.1 Conditional Statements</h4><h4>If-Else Statement</h4><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>int main() {<br>    int num;<br>    cout &lt;&lt; &quot;Enter a number: &quot;;<br>    cin &gt;&gt; num;<br><br>    if (num &gt; 0)<br>        cout &lt;&lt; &quot;Positive Number&quot; &lt;&lt; endl;<br>    else if (num &lt; 0)<br>        cout &lt;&lt; &quot;Negative Number&quot; &lt;&lt; endl;<br>    else<br>        cout &lt;&lt; &quot;Zero&quot; &lt;&lt; endl;<br><br>    return 0;<br>}</pre><h4>Switch Statement</h4><p>Used for multiple conditions.</p><pre>int day = 3;<br>switch(day) {<br>    case 1: cout &lt;&lt; &quot;Monday&quot;; break;<br>    case 2: cout &lt;&lt; &quot;Tuesday&quot;; break;<br>    case 3: cout &lt;&lt; &quot;Wednesday&quot;; break;<br>    default: cout &lt;&lt; &quot;Invalid day&quot;;<br>}</pre><h4>6.2 Iterative Statements (Loops)</h4><p>Loops <strong>repeat a block of code</strong>.</p><h4>For Loop</h4><pre>for(int i = 0; i &lt; 5; i++) {<br>    cout &lt;&lt; i &lt;&lt; &quot; &quot;;<br>}</pre><h4>While Loop</h4><pre>int i = 0;<br>while(i &lt; 5) {<br>    cout &lt;&lt; i &lt;&lt; &quot; &quot;;<br>    i++;<br>}</pre><h4>Do-While Loop</h4><pre>int i = 0;<br>do {<br>    cout &lt;&lt; i &lt;&lt; &quot; &quot;;<br>    i++;<br>} while(i &lt; 5);</pre><p>✔ <strong>Use </strong><strong>break to exit a loop early</strong>.<br> ✔ <strong>Use </strong><strong>continue to skip an iteration</strong>.</p><h3>7. Arrays in C++</h3><p>Arrays store <strong>multiple values of the same type</strong> in a contiguous memory location.</p><h4>Declaring and Initializing Arrays</h4><pre>int arr[5] = {10, 20, 30, 40, 50};</pre><h4>Accessing Elements</h4><pre>cout &lt;&lt; arr[0]; // Prints first element</pre><h4>Looping Through an Array</h4><pre>for(int i = 0; i &lt; 5; i++) {<br>    cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;<br>}</pre><h4>Multi-Dimensional Arrays</h4><p>Used for matrices and grids.</p><pre>int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};</pre><h4>Using Arrays with Functions</h4><pre>void display(int arr[], int size) {<br>    for(int i = 0; i &lt; size; i++) {<br>        cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;<br>    }<br>}</pre><h3>8. Conclusion</h3><p>C++ provides a <strong>strong foundation for programming</strong> through <strong>structured program construction, efficient I/O handling, preprocessor directives, data types, control statements, and arrays</strong>. Mastering these topics enables developers to build <strong>complex applications with optimized performance</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11fbe6afd9eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>